0
0
Kotlinprogramming~20 mins

Platform types and null safety in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Platform Types Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Understanding platform types and null safety
What is the output of this Kotlin code when calling a Java method that returns a platform type?
Kotlin
fun main() {
    val javaString: String = getJavaString()
    println(javaString.length)
}

// Simulated Java method returning platform type
fun getJavaString(): String? = null
APrints 0
BThrows a NullPointerException at runtime
CCompilation error due to null assignment
DPrints 'null'
Attempts:
2 left
💡 Hint
Platform types allow nulls but Kotlin treats them as non-null by default.
Predict Output
intermediate
2:00remaining
Safe call operator with platform types
Given a platform type from Java, what will this Kotlin code print?
Kotlin
fun main() {
    val javaString = getJavaString()
    println(javaString?.length ?: "null length")
}

fun getJavaString(): String? = null
Anull length
BThrows NullPointerException
C0
DCompilation error
Attempts:
2 left
💡 Hint
The safe call operator ?. prevents NullPointerException.
🔧 Debug
advanced
2:00remaining
Identify the cause of NullPointerException with platform types
Why does this Kotlin code throw a NullPointerException at runtime?
Kotlin
fun main() {
    val javaList: List<String> = getJavaList()
    println(javaList.size)
}

fun getJavaList(): List<String>? = null
ABecause platform types are treated as non-nullable but can be null at runtime
BBecause Kotlin does not allow null lists at all
CBecause getJavaList() returns an empty list, not null
DBecause size property is not available on platform types
Attempts:
2 left
💡 Hint
Platform types come from Java and Kotlin assumes non-null but no guarantee.
📝 Syntax
advanced
2:00remaining
Correctly declaring a platform type variable
Which Kotlin declaration correctly represents a platform type variable from Java that might be null?
Aval javaStr: String! = getJavaString()
Bval javaStr: String? = getJavaString()
Cval javaStr = getJavaString()
Dval javaStr: String = getJavaString()
Attempts:
2 left
💡 Hint
Platform types are not explicitly declared in Kotlin code.
🚀 Application
expert
3:00remaining
Handling platform types safely in Kotlin
You receive a platform type String! from a Java method that might be null. Which Kotlin code snippet safely handles this value to avoid runtime exceptions?
A
val safeStr: String = javaStr
println(safeStr.length)
B
val safeStr: String = javaStr ?: ""
println(safeStr.length)
C
val safeStr: String = javaStr!!
println(safeStr.length)
D
val safeStr: String? = javaStr
println(safeStr?.length ?: 0)
Attempts:
2 left
💡 Hint
Convert platform type to nullable type to safely check for null.