Junior — Middle
Is it possible in Kotlin for a situation to occur where a NullPointerException is thrown during code execution?
sobes.tech AI
Answer from AI
Yes, in Kotlin, there is a situation where a NullPointerException can occur despite the built-in null safety system. This can happen if:
- The !! operator (not-null assertion) is used, which explicitly tells the compiler that the value is not null, but if it is null, an exception will be thrown.
- Interaction with Java code, where null safety is not guaranteed, and Kotlin cannot always check nullability.
- Incorrect use of lateinit variables, if they are accessed before initialization.
Example with the !! operator:
val s: String? = null
val length = s!!.length // NullPointerException will occur here