Understanding Null Safety in Kotlin
Tags: android, kotlin
Published: 2020-07-17 23:47:49


> Programming errors involving nulls have been the source of countless bugs.

---

Kotlin is fighting NullPointerException (NPE) by introducing non-nullable and nullable variables, and now we can distinguish between references that can contain null values and those that cannot, and it is done natively.

By default, variables cannot contain nulls. BUT we can indicate that a variable can contain them using just a question mark (?). Take a look at the next example: 

```kotlin
var dinosaur: String = null
// error: null can not be a value of a non-null type String

val dinosaur: String? = null // That’s better
print(dinosaur)
//output -> null
```

Easy peasy ... It's important to know some operators that can help us evaluate these null assignments. 

### ? Operator (Safe calls)

This operator helps us to evaluate a variable that was previously defined as a variable that can hold nulls like in the next example:

```kotlin
val dinosaur: String? = null

print(dinosaur?.length)
// output-> null
```
We can also do the same with a non-nullable variable but this is an unnecessary safe call:

```kotlin
val dinosaur: String = "I'm a dinosaur"
print(dinosaur?.length)
//output -> 14
```

This is another example of using it with data classes, for example:

```kotlin
// we define that isSpacy can hold nulls
data class Taco(var name: String, var isSpacy: Boolean?)
```

Then we can do something like this:

```kotlin
// here we set isSapacy as null
val myTaco = Taco("Pastor", null) 
```

So we have **myTaco** with **isSpacy** as null so the next code won’t compile:

```kotlin
myTaco.isSpacy.equals ("false”)
// error: only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type Boolean?
```

Instead of that, we should do a safe call like this:

```kotlin
myTaco.isSpacy?.equals(false)
//output -> null
```

In the previous example, Kotlin will evaluate **myTaco.isSpacy** and if it's null it will return null, else it will continue the execution of the code.

### The ?: Operator or Elvis Operator

This Kotlin operator is a simple “if” that help us to easily and clear check if a value is null.

So this odd code:

```kotlin
val fruitName: String? = null

val nameLength: Int = if (fruitName! = null) fruitName.length else -1
```

Can be written like this:

```kotlin
val nameLength: Int = fruitName?.length ?: -1
```

If **fruitName** is null then return -1 else return whatever **fruitName.length** is.

### The !! Operator, Bang Bang operator or double-bang operator

So far, so good, but what happens if I really like NullPointerExceptions. Where are they? In this case, Kotlin let up to us manage the NPE. So, here is where we can use the bang-bang operator (!!)

Remainder: This is only for NPE-lovers

```kotlin
val size = fruitName!!.length
```

Here we are telling Kotlin that we want to get an NPE in case of **fruitName** has a null value, So we are asking for an NPE explicitly and it is well known that if we can, avoid this operator.

___
As we saw, Kotlin provides us an easy option to handle the pain of getting NullPointerExceptions, and almost always it does not allow us to compile our code until we fix them. So now, let's avoid them wisely.