Junior — Middle
What happens if you access an object of nullable type directly without a check in Kotlin?
sobes.tech AI
Answer from AI
In Kotlin, if you access an object with a nullable type directly without a check (for example, calling a method or accessing a property), a NullPointerException will be thrown at runtime.
For example:
val s: String? = null
println(s.length) // Compilation error
println(s!!.length) // Compiles, but throws NullPointerException at runtime
To avoid this, you should either use the safe call ?., or check the object for null before accessing:
println(s?.length) // Returns null if s == null
if (s != null) {
println(s.length)
}
Thus, directly accessing a nullable object without a check leads to an abrupt program termination with an exception.