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] "Unknown"
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using !! instead of ?: causes a crash if the value is null.
Using ?. only safely accesses properties but doesn't provide a default.
✗ Incorrect
The Elvis operator ?: returns the left value if it's not null, otherwise the right value.
2fill in blank
mediumComplete the code to safely get the length of a nullable string or return 0 using the Elvis operator.
Kotlin
val text: String? = null val length = text?.length [1] 0
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using !! causes an exception if text is null.
Using == is a comparison, not a fallback.
✗ Incorrect
The Elvis operator ?: returns 0 if text?.length is null.
3fill in blank
hardFix the error in the code by completing the Elvis operator usage to provide a default value.
Kotlin
fun getUserName(user: User?): String {
return user?.name [1] "Guest"
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using !! causes a crash if user or name is null.
Using ?. does not provide a default value.
✗ Incorrect
Use ?: to return "Guest" if user?.name is null.
4fill in blank
hardFill both blanks to use the Elvis operator and safe call to get the length or return -1.
Kotlin
fun getLength(str: String?): Int {
return str[1]length [2] -1
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using !! can cause exceptions if str is null.
Using == is a comparison, not a fallback.
✗ Incorrect
Use ?. to safely access length and ?: to provide -1 if null.
5fill in blank
hardFill all three blanks to chain safe calls and Elvis operators to get a nested property or default.
Kotlin
fun getCountry(user: User?): String {
return user[1]address[2]country [3] "Unknown"
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using !! can cause crashes if any property is null.
Using == is a comparison, not a fallback.
✗ Incorrect
Use ?. to safely access nested properties and ?: to provide a default.