0
0
Kotlinprogramming~10 mins

Why null safety is Kotlin's defining feature - Test Your Understanding

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

Complete the code to declare a nullable variable in Kotlin.

Kotlin
var name: String[1] = null
Drag options to blanks, or click blank then click option'
A*
B!
C?
D#
Attempts:
3 left
💡 Hint
Common Mistakes
Using '!' instead of '?' to mark nullable types.
2fill in blank
medium

Complete the code to safely access the length of a nullable string.

Kotlin
val length = name[1]length
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.
3fill in blank
hard

Fix the error in the code to throw an exception if the nullable variable is null.

Kotlin
val nonNullName = name[1]
Drag options to blanks, or click blank then click option'
A?
B!!
C?.
D?:
Attempts:
3 left
💡 Hint
Common Mistakes
Using '?' which allows nulls without exception.
4fill in blank
hard

Fill both blanks to provide a default value if the nullable variable is null.

Kotlin
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 '!!' which throws instead of providing a default.
5fill in blank
hard

Fill all three blanks to filter a list of nullable strings and print their lengths safely.

Kotlin
val names: List<String?> = listOf("Anna", null, "Bob")
val lengths = names.filterNotNull().map { it[1]length }
lengths.forEach { println(it[2]toString()[3]) }
Drag options to blanks, or click blank then click option'
A.
B+
C()
D?.
Attempts:
3 left
💡 Hint
Common Mistakes
Using safe call operator after filtering nulls, which is unnecessary.