liveBook · Manning

!! operator

As explained in Kotlin in Action, 2E

The non-null assertion operator `!!` asserts that a nullable expression is non-null and throws an exception if that assertion is false.

The Kotlin non-null assertion operator `!!` converts a nullable value to a non-nullable type by promising the compiler that the value is not null. If that promise is false, the assertion throws an exception immediately. section 7.7 section 7.13

A direct assertion

fun ignoreNulls(str: String?) { val strNotNull: String = str!! println(strNotNull.length) } fun main() { ignoreNulls(null) } Here, `str!!` performs the assertion and produces a `String`. Passing `null` throws at the assertion line, before `length` is accessed. The operator is deliberately blunt: prefer a compiler-verifiable null check when one is practical. section 7.7

Use `!!` when a safety check occurs elsewhere and the compiler cannot connect that check to a later use. In an action class, an update method can ensure an action is enabled only when a selection exists, while the execution method asserts the selected index before using it. This keeps the invariant explicit but still makes a broken promise fail at runtime. section 7.7

The operator is an unsafe alternative to safe calls, the Elvis operator, `let`, and safe casts. It is especially relevant at Java boundaries, where Kotlin generates assertions for parameters declared non-null because non-Kotlin code may still pass null. section 7.12.2 section 7.13

How Kotlin in Action, 2E covers it

How deep it goes
Explains conversion, immediate runtime failure, design intent, and an action-class case, but stops short of compiler implementation internals.
Examples
Demonstrates a nullable string, a separated action enablement check, a selected list index, and Java method parameters.
What it assumes
Assumes nullable and non-nullable Kotlin types while teaching the assertion and contrasting it with safer nullable-value operations.
What you can do after
Diagnose where a violated non-null promise fails and apply `!!` selectively when a separately enforced invariant cannot be expressed to the compiler.
How it connects
Connects `!!` with nullable types, safe calls, the Elvis operator, `let`, safe casts, platform types, and Java interoperability.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.