?
: allow null?.
: safe access!!
: not null assertionas?
: safe casts
NPE
The only possible causes of an NPE in Kotlin are:
- An explicit call to
throw NullPointerException()
. - Usage of the not-null assertion operator
!!
. - Data inconsistency during initialization, such as when:
- An uninitialized
this
available in a constructor is used somewhere else (a “leakingthis
”). - A superclass constructor calling an open member whose implementation in the derived class uses an uninitialized state.
- An uninitialized
- Java interoperation:
- Attempts to access a member of a
null
reference of a platform type. - Nullability issues with generic types. For example, a piece of Java code adding
null
into a KotlinMutableList<String>
, which would requireMutableList<String?>
to handle it properly. - Other issues caused by external Java code.
- Attempts to access a member of a
- Null safety | Kotlin Documentation