0
0
Kotlinprogramming~10 mins

Elvis operator (?:) for default values in Kotlin - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
A?:
B!!
C?.
D==
Attempts:
3 left
💡 Hint
Common Mistakes
Using '!!' which throws an exception if null.
Using '?.' which is for safe calls, not default values.
2fill in blank
medium

Complete 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'
A!!
B?:
C?.
D==
Attempts:
3 left
💡 Hint
Common Mistakes
Using '!!' which causes an exception if null.
Using '?.' which is for safe calls, not default values.
3fill in blank
hard

Fix 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'
A==
B!!
C?.
D?:
Attempts:
3 left
💡 Hint
Common Mistakes
Using '!!' which throws an exception if null.
Using '?.' which is for safe calls, not default values.
4fill in blank
hard

Fill 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'
A?:
B>
C>=
D!!
Attempts:
3 left
💡 Hint
Common Mistakes
Using '!!' which throws an exception if the word is null.
Using '>=' which would include words of length 3.
5fill in blank
hard

Fill 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'
A.uppercase()
B?:
C>
D!!
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.