Junior — Middle
Can you encounter a NullPointerException in Kotlin?
sobes.tech AI
Answer from AI
In Kotlin, you can encounter a NullPointerException, even though the language is designed for safe handling of nulls. This can happen in the following cases:
- When using the
!!operator, which explicitly tells the compiler that the value is not null, but if it is null — aNullPointerExceptionwill be thrown. - When interacting with Java code, where null-safety is not guaranteed.
- In some cases related to reflection or low-level operations.
Example:
val s: String? = null
println(s!!.length) // will throw NullPointerException
Therefore, despite the built-in type system with null-safety, NullPointerException exceptions are possible in Kotlin and require caution.