In Kotlin, it's possible to have a
null value. To help prevent issues with
null values in your programs, Kotlin has null safety in place. Null safety detects potential problems with
null values at compile time, rather than at run time.
Null safety is a combination of features that allow you to:
explicitly declare when
nullvalues are allowed in your program.
use safe calls to properties or functions that may contain
declare actions to take if
nullvalues are detected.
Kotlin supports nullable types which allows the possibility for the declared type to have
null values. By default, a type is not allowed to accept
null values. Nullable types are declared by explicitly adding
? after the type declaration.
Check for null values
You can check for the presence of
null values within conditional expressions. In the following example, the
describeString() function has an
if statement that checks whether
maybeString is not
null and if its
length is greater than zero:
Use safe calls
To safely access properties of an object that might contain a
null value, use the safe call operator
?.. The safe call operator returns
null if the object's property is
null. This is useful if you want to avoid the presence of
null values triggering errors in your code.
In the following example, the
lengthString() function uses a safe call to return either the length of the string or
The safe call operator can also be used to safely call an extension or member function. In this case, a null check is performed before the function is called. If the check detects a
null value, then the call is skipped and
null is returned.
In the following example,
null so the invocation of
.uppercase() is skipped and
null is returned:
Use Elvis operator
You can provide a default value to return if a
null value is detected by using the Elvis operator
Write on the left-hand side of the Elvis operator what should be checked for a
null value. Write on the right-hand side of the Elvis operator what should be returned if a
null value is detected.
In the following example,
null so the safe call to access the
length property returns a
null value. As a result, the Elvis operator returns
For more information about null safety in Kotlin, see Null safety.
You have the
employeeById function that gives you access to a database of employees of a company. Unfortunately, this function returns a value of the
Employee? type, so the result can be
null. Your goal is to write a function that returns the salary of an employee when their
id is provided, or
0 if the employee is missing from the database.
Congratulations! Now that you have completed the Kotlin tour, check out our tutorials for popular Kotlin applications: