0
0
Kotlinprogramming~20 mins

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

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Kotlin Null Safety Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Kotlin code with null safety?
Consider the following Kotlin code snippet. What will it print when run?
Kotlin
fun main() {
    val name: String? = null
    println(name?.length ?: "No name")
}
AThrows NullPointerException
B0
Cnull
DNo name
Attempts:
2 left
💡 Hint
Look at the safe call operator and the Elvis operator usage.
🧠 Conceptual
intermediate
2:00remaining
Why does Kotlin distinguish between nullable and non-nullable types?
Why is it important that Kotlin has separate types for nullable and non-nullable variables?
ATo allow variables to change type at runtime
BTo prevent null pointer exceptions by forcing explicit handling of nulls
CTo make all variables nullable by default
DTo make the code run faster by avoiding null checks
Attempts:
2 left
💡 Hint
Think about common errors in other languages caused by null values.
🔧 Debug
advanced
2:00remaining
What error does this Kotlin code produce?
Examine the code below. What error will the Kotlin compiler report?
Kotlin
fun main() {
    val text: String = null
    println(text.length)
}
ANull can not be a value of a non-null type String
BUnresolved reference: length
CNullPointerException at runtime
DNo error, prints 0
Attempts:
2 left
💡 Hint
Look at the variable declaration and its assigned value.
📝 Syntax
advanced
2:00remaining
Which Kotlin code snippet correctly uses the safe call operator?
Select the code snippet that safely accesses the length of a nullable String variable 'input'.
Aval length = input?.length
Bval length = input ?: input.length
Cval length = input!! .length
Dval length = input.length
Attempts:
2 left
💡 Hint
Safe call operator is used with '?.' syntax.
🚀 Application
expert
3:00remaining
What is the output of this Kotlin code demonstrating null safety with let?
Analyze the following Kotlin code and select the output it produces.
Kotlin
fun main() {
    val name: String? = "Kotlin"
    name?.let {
        println("Name length is ${it.length}")
    } ?: println("Name is null")
}
AName is null
BName length is null
CName length is 6
DThrows NullPointerException
Attempts:
2 left
💡 Hint
The 'let' function runs only if the variable is not null.