Programming in Kotlin: Fundamentals

Aug 9 2022 · Kotlin 1.6, Android 12, IntelliJ IDEA CE 2022.1.3

Part 3: Functions & Nullability

21. Challenge: Use Nullables

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 20. Create & Consume Nullables Next episode: 22. Write Custom Functions

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

To get a hang of nullable values, and how to work around them using checks and smart casting, I’ve prepared a challenge for you.

Challenge:
Declare a variable of type String? called `password` and assign a value to it.

Using an if expression, check the level of password strength, 
and assign an appropriate message to another constant named `message`. 

Then print out the message.

Levels are designed as follows:

0 characters or `null` -> “Ehm, you need a password to keep safe!”
1-5 characters -> “Weak password! Try adding a few more symbols to it!”
6-10 characters -> “Medium-strength password.”
11-15 characters -> “No one is getting through this!”
15+ characters -> "Ironclad
val password: String? = "12345"
val message = if (password == null || password.isEmpty()) {
  "Ehm, you need a password to keep safe!"
}
...
 else if (password.length in 1..5) {
  "Weak password! Try adding a few more symbols to it!"
} else if (password.length in 6..10) {
  "Medium-strength password."
} else if (password.length in 11..15) {
  "No one is getting through this!"
} else {
  "Ironclad"
}

println(message)
val password: String? = "12345"
val passwordLength = password?.length ?: 0

val message = if (passwordLength == 0) {
  "Ehm, you need a password to keep safe!"
} else if (passwordLength in 1..5) {
  "Weak password! Try adding a few more symbols to it!"
} else if (passwordLength in 6..10) {
  "Medium-strength password."
} else if (passwordLength in 11..15) {
  "No one is getting through this!"
} else {
  "Ironclad"
}