GardenMobile & interfaces

Kotlin nullable access and the non-null assertion

A small comparison of direct access, safe calls, and the !! operator.

For a nullable String?, a safe call and a non-null assertion express different expectations. A safe call allows the value to be absent; !! asserts that it is present and fails if that assumption is wrong.

The original comparison assumes a is declared nullable and has not already been smart-cast:

Value of a: String? a.length a?.length a!!.length
"cat" Compile-time error 3 3
null Compile-time error null Throws a null-pointer exception

The useful question is whether absence is part of the expected data. !! does not validate or repair that data; it turns an assumption into a runtime requirement.

See Kotlin’s null-safety documentation for safe calls, smart casts, and non-null assertions.

← Back to the garden