0
0
Kotlinprogramming~10 mins

Elvis operator deep usage 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] "Unknown"
Drag options to blanks, or click blank then click option'
A?.
B==
C!!
D?:
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.
2fill in blank
medium

Complete 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'
A?:
B?.
C!!
D==
Attempts:
3 left
💡 Hint
Common Mistakes
Using !! causes an exception if text is null.
Using == is a comparison, not a fallback.
3fill in blank
hard

Fix 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'
A!!
B?:
C?.
D==
Attempts:
3 left
💡 Hint
Common Mistakes
Using !! causes a crash if user or name is null.
Using ?. does not provide a default value.
4fill in blank
hard

Fill 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'
A?.
B?:
C!!
D==
Attempts:
3 left
💡 Hint
Common Mistakes
Using !! can cause exceptions if str is null.
Using == is a comparison, not a fallback.
5fill in blank
hard

Fill 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'
A?.
B?:
C!!
D==
Attempts:
3 left
💡 Hint
Common Mistakes
Using !! can cause crashes if any property is null.
Using == is a comparison, not a fallback.