Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to assign a default value using the Elvis operator.
Kotlin
val name: String? = null val displayName = name [1] "Guest"
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '!!' which throws an exception if null.
Using '?.' which is for safe calls, not default values.
✗ Incorrect
The Elvis operator ?: returns the left value if it's not null; otherwise, it returns the right value.
2fill in blank
mediumComplete the code to print a default message when the nullable variable is null.
Kotlin
fun greet(user: String?) {
println(user [1] "Anonymous")
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '!!' which causes an exception if null.
Using '?.' which is for safe calls, not default values.
✗ Incorrect
The Elvis operator ?: provides a default value when the left side is null.
3fill in blank
hardFix the error in the code by using the correct operator to provide a default value.
Kotlin
val length = text?.length [1] 0
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '!!' which throws an exception if null.
Using '?.' which is for safe calls, not default values.
✗ Incorrect
The Elvis operator ?: returns 0 if text?.length is null.
4fill in blank
hardFill both blanks to create a map of words to their lengths, but only include words longer than 3 characters.
Kotlin
val words = listOf("cat", null, "elephant", "dog", "lion") val lengths = words.associateWith { it?.length [1] 0 } .filter { it.value [2] 3 }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '!!' which throws an exception if the word is null.
Using '>=' which would include words of length 3.
✗ Incorrect
Use the Elvis operator ?: to return 0 if it?.length is null (when word is null), and > to filter lengths greater than 3.
5fill in blank
hardFill all three blanks to create a map of uppercase words to their lengths, including only words with length greater than 3.
Kotlin
val words = listOf("apple", null, "bat", "carrot", "dog") val result = words.associate { (it ?: "UNKNOWN")[1] to it?.length [2] 0 } .filter { it.value [3] 3 }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '!!' in the second blank, which throws an exception if word is null.
Using '>=' in the third blank, which includes length 3.
✗ Incorrect
Use '.uppercase()' to convert the key to uppercase (null handled as "UNKNOWN"), the Elvis operator ?: to default length to 0 if null, and '>' to filter lengths greater than 3.