Interactive Kotlin Basics

romainbsl
2,103 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content
Previous: Collections

Null safety

A feature that makes Kotlin more valuable is the management of null.

Kotlin help you to avoid the in-famous NPE (NullPointerException). You have to understand that you may have NPE, even with Kotlin, but this will happen if you don't make enough effort. Kotlin will help you think about how you code in a good way.

In Kotlin a non-nullable string will be written String and a nullable will be String?.

1
4
5
6
7
8
// {...}
// Variable that cannot be `null`
var str: String = "K."
// Variable that can be null
var str2: String?
// {...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Also, Kotlin provides a way to avoid NPE, when calling multiple level of nullable values.

1
7
8
9
10
// {...}
val me = Person("Romain", "Bsl", Address(city = "Nivelles"))
// Nothing will be printed for me.address?.street
println("${me.firstname} lives in ${me.address?.city} ${me.address?.street}")
// {...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content