Nullable types and non-nullable types
Kotlin's type system is aimed at eliminating the danger of null references, also known as The Billion Dollar Mistake.
One of the most common pitfalls in many programming languages, including Java, is that accessing a member of a null reference will result in a null reference exception. In Java this would be the equivalent of a
NullPointerException, or an NPE for short.
The only possible causes of an NPE in Kotlin are:
An explicit call to
Usage of the
!!operator that is described below.
Data inconsistency with regard to initialization, such as when:
thisavailable in a constructor is passed and used somewhere (a "leaking
A superclass constructor calls an open member whose implementation in the derived class uses an uninitialized state.
Attempts to access a member of a
nullreference of a platform type;
Nullability issues with generic types being used for Java interoperation. For example, a piece of Java code might add
nullinto a Kotlin
MutableList<String>, therefore requiring a
MutableList<String?>for working with it.
Other issues caused by external Java code.
In Kotlin, the type system distinguishes between references that can hold
null (nullable references) and those that cannot (non-nullable references). For example, a regular variable of type
String cannot hold
To allow nulls, you can declare a variable as a nullable string by writing
Now, if you call a method or access a property on
a, it's guaranteed not to cause an NPE, so you can safely say:
But if you want to access the same property on
b, that would not be safe, and the compiler reports an error:
But you still need to access that property, right? There are a few ways to do so.
Checking for null in conditions
First, you can explicitly check whether
null, and handle the two options separately:
The compiler tracks the information about the check you performed, and allows the call to
length inside the
if. More complex conditions are supported as well:
Note that this only works where
b is immutable (meaning it is a local variable that is not modified between the check and its usage or it is a member
val that has a backing field and is not overridable), because otherwise it could be the case that
b changes to
null after the check.
Your second option for accessing a property on a nullable variable is using the safe call operator
b is not null, and
null otherwise. The type of this expression is
Safe calls are useful in chains. For example, Bob is an employee who may be assigned to a department (or not). That department may in turn have another employee as a department head. To obtain the name of Bob's department head (if there is one), you write the following:
Such a chain returns
null if any of the properties in it is
To perform a certain operation only for non-null values, you can use the safe call operator together with
A safe call can also be placed on the left side of an assignment. Then, if one of the receivers in the safe calls chain is
null, the assignment is skipped and the expression on the right is not evaluated at all:
Extension functions can be defined on a nullable receiver. This way you can specify behaviour for null values without the need to use null-checking logic at each call-site.
For example, the
toString() function is defined on a nullable receiver. It returns the String "null" (as opposed to a
null value). This can be helpful in certain situations, for example, logging:
If you want your
toString() invocation to return a nullable string, use the safe-call operator
When you have a nullable reference,
b, you can say "if
b is not
null, use it, otherwise use some non-null value":
Instead of writing the complete
if expression, you can also express this with the Elvis operator
If the expression to the left of
?: is not
null, the Elvis operator returns it, otherwise it returns the expression to the right. Note that the expression on the right-hand side is evaluated only if the left-hand side is
return are expressions in Kotlin, they can also be used on the right-hand side of the Elvis operator. This can be handy, for example, when checking function arguments:
The !! operator
The third option is for NPE-lovers: the not-null assertion operator (
!!) converts any value to a non-nullable type and throws an exception if the value is
null. You can write
b!!, and this will return a non-null value of
b (for example, a
String in our example) or throw an NPE if
Thus, if you want an NPE, you can have it, but you have to ask for it explicitly and it won't appear out of the blue.
Regular casts may result in a
ClassCastException if the object is not of the target type. Another option is to use safe casts that return
null if the attempt was not successful:
Collections of a nullable type
If you have a collection of elements of a nullable type and want to filter non-nullable elements, you can do so by using