Skip to main content

Null safety in Kotlin

Kotlin is designed to be null safe!
  • A null pointer exception occurs when we try to use variables that have null value.
  • Kotlin is designed in such a way that it greatly reduces the possibility of null pointer exceptions.
  • Variables in Kotlin can not hold a null value by default
  • Nullable variable i.e. variables that can hold null values, needs to be explicitly defined so.

Let's understand a few null safety concepts in Kotlin with these simple code snippets.
Remember, how to define variables? We are going to go ahead and define a variable and try to assign null value to it.
var msg: String
msg = null
This isn't allowed in kotlin since we didn't explicitly specify that the variable msg can contain null value. If you try to run the program, you will get an error.

But sometimes, we need a variable to have null value now and then some other value later. Adding a question mark at the end of variable definition allows us to explicitly declare that this variable may contain null values.
var msg: String?
// now we may store null values in msg
msg = null
Alright, so we got a variable which can contain null value. Now how do we access or use it safely without getting any NPEs (null pointer exceptions)? Checkout these bite sized posts! :)
  1. Safe call operator
  2. Elvis operator
  3. Double bang opeartor

Comments