Junior — Middle
How is null safety ensured in Kotlin and how is it implemented in practice?
sobes.tech AI
Answer from AI
In Kotlin, null safety is built into the type system, which distinguishes between nullable and non-nullable types.
- Types without
?cannot contain null, e.g.,String. - Types with
?can contain null, e.g.,String?.
This allows the compiler to catch potential errors at compile time, preventing NullPointerException.
Practical mechanisms for working with null:
- Safe call operator
?.— calls a method or accesses a property only if the object is not null. - Elvis operator
?:— provides a default value if the expression on the left is null. - Not-null assertion
!!— forcibly asserts that the value is not null, throwing an exception if it is.
Example:
val name: String? = null
println(name?.length) // Prints null, does not throw error
println(name ?: "Unknown") // Prints "Unknown"
// println(name!!.length) // Throws NullPointerException
Thus, Kotlin helps write safer code, minimizing null-related errors.