0
0
Kotlinprogramming~20 mins

Non-nullable types by default in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Null Safety Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of accessing a nullable variable
What is the output of this Kotlin code snippet?
Kotlin
fun main() {
    val name: String? = null
    println(name?.length ?: "No length")
}
Anull
BNo length
C0
DThrows NullPointerException
Attempts:
2 left
💡 Hint
Look at the safe call operator and the Elvis operator usage.
Predict Output
intermediate
2:00remaining
Behavior of non-nullable variable assignment
What happens when you try to assign null to a non-nullable variable in Kotlin?
Kotlin
fun main() {
    val number: Int = null
    println(number)
}
ACompilation error
BPrints null
CPrints 0
DThrows NullPointerException at runtime
Attempts:
2 left
💡 Hint
Remember Kotlin's default type nullability.
🔧 Debug
advanced
2:00remaining
Identify the cause of NullPointerException
Why does this Kotlin code throw a NullPointerException at runtime?
Kotlin
fun main() {
    val text: String? = null
    val length: Int = text!!.length
    println(length)
}
ABecause println cannot print null values
BBecause length is declared as Int instead of Int?
CBecause text is nullable and !! forces non-null, causing exception
DBecause text is not initialized
Attempts:
2 left
💡 Hint
Check the use of the !! operator on a null value.
🧠 Conceptual
advanced
2:00remaining
Understanding Kotlin's type system default
Which statement best describes Kotlin's type system regarding nullability?
AAll types are nullable by default, requiring explicit non-null declaration
BKotlin does not support nullable types
CNullability is not checked by the compiler in Kotlin
DAll types are non-nullable by default, requiring explicit nullable declaration
Attempts:
2 left
💡 Hint
Think about how Kotlin prevents null pointer errors.
Predict Output
expert
2:00remaining
Output of complex nullable chaining
What is the output of this Kotlin code?
Kotlin
fun main() {
    val map: Map<String, String?> = mapOf("key" to null)
    val length = map["key"]?.length ?: -1
    println(length)
}
A-1
BThrows NullPointerException
Cnull
D0
Attempts:
2 left
💡 Hint
Check the safe call and Elvis operator on a nullable map value.