Chapter 8. nulls and exceptions: Safe and Sound


Everybody wants to write code that’s safe.

And the great news is that Kotlin was designed with code-safety at its heart. We’ll start by showing you how Kotlin’s use of nullable types means that you’ll hardly ever experience a NullPointerException during your entire stay in Kotlinville. You’ll discover how to make safe calls, and how Kotlin’s Elvis operator stops you being all shook up. And when we’re done with nulls, you’ll find out how to throw and catch exceptions like a pro.

How do you remove object references from variables?

As you already know, if you want to define a new Wolf variable and assign a Wolf object reference to it, you can do so using code like this:

var w = Wolf()

The compiler spots that you want to assign a Wolf object to the w variable, so it infers that the variable must have a type of Wolf:


Once the compiler knows the variable’s type, it ensures that it can only hold references to Wolf objects, including any Wolf subtypes. So if the variable is defined using var, you can update its value so that it holds a reference to an entirely different Wolf object using, for example:

w = Wolf()

But what if you want ...

Get Head First Kotlin now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.