Safe Calls and the Not-Null Assertion
Learn to handle null values and implement exception-handling functions for safer code.
We'll cover the following
Safe calls
The simplest way to call a method or a property on a nullable value is with a safe call, which is a question mark and a dot (?.
) instead of just a regular dot (.
).
Safe calls work as follows:
If a value is
null
, it does nothing and returnsnull
.If a value is not
null
, it works like a regular call.
Points to remember:
The result of a safe call is always a nullable type because a safe call returns
null
when it is called on anull
. This means that nullability propagates.If we need to find out the length of a user’s name, calling
user?.name.length
will not compile. Even thoughname
is not nullable, the result ofuser?.name
isString?
, so we need to use a safe call again:user?.name?.length
.
Get hands-on with 1200+ tech skills courses.