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

Lesson Complete

Play Next Lesson
Next
Save for later
About this episode
See versions
See forum comments
Cinema mode Mark as Complete Download course materials
Previous episode: 20. Create & Consume Nullables Next episode: 22. Write Custom Functions

This video was last updated on Aug 9 2022

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.

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"
}