Kotlin miniguide #16 Null safety

Unless explicitly declared, a reference in kotlin cannot hold the value null

When a reference is nullable, a check on the reference must be done before accessing the object, otherwise we will get a compiler error:


var s : String = "a"

s = null //<strong>does not compile </strong>

var p: String? = "a"

p = null //<strong>ok</strong>

p.lenght //<strong>does not compile </strong>

p?.length //<strong>ok</strong>

Lascia un commento