Part 03 / Topic 5 of 8
!! and why this course bans it
!! ("the not-null assertion operator," almost always just called "bang-bang") converts any
nullable value into its non-null type, on the spot, with one rule: if the value actually is
null, it throws a plain NullPointerException, right there.
println(pincode!!.length)
Run for real, on a pincode that doesn't exist:
$ kotlinc BangBangTest.kt -include-runtime -d bb.jar
$ java -jar bb.jar
about to force-unwrap a null with !!
Exception in thread "main" java.lang.NullPointerException
at BangBangTestKt.main(BangBangTest.kt:5)
at BangBangTestKt.main(BangBangTest.kt)
That exception carries no message at all — not which value was null, not why, not what to
do about it. !! is Kotlin's escape hatch back into exactly the bug Part 1's "What Kotlin is"
section said this language doesn't have, and it compiles silently every time, waiting for the
one input that proves the assertion wrong. This course never uses it, in any example or any
solution, for that reason.
If you genuinely believe a value can never be null at a given point and want to fail loudly if you're wrong, say so with a message instead of asserting it away blind:
val confirmed = requireNotNull(pincode) { "no pincode on file for Hyderabad" }
requireNotNull threw: no pincode on file for Hyderabad
requireNotNull throws IllegalArgumentException with the message you gave it — a reader of
the crash log, three months from now, learns what was missing instead of staring at a bare
NullPointerException with a stack trace and nothing else. But almost every real case doesn't
need either one: handle the missing value directly, with ?: or an early return, the way
sections 3 and 4 already did.
$ kotlinc 05_bang_bang.kt -include-runtime -d 05.jar
$ java -jar 05.jar
!! on a null value threw: java.lang.NullPointerException
requireNotNull threw: no pincode on file for Hyderabad
safe length = 0
Full program: examples/05_bang_bang.kt.
Done here? The practice set for Part 3 — including the solutions — is on the part page.