Leveraging Null Safety in Kotlin

January 17, 2019

One of the biggest annoyance in Java is always having to deal with null. Looking at any large Java code base, you are bound to see the the expression ... == null to check for null which is such an inconvenience. In many other languages (ie Swift) they get around this with the idea of optionals. Kotlin was also able to achieve this as well, let's see how:

var b: String? = "abc"
b = null // ok
print(b)


var b: String? = null
if (b != null && b.isNotEmpty()) {
    print(b)
}

if (b?.isNotEmpty() == true){
  print(b)
}

bob?.department?.head?.name

val listWithNulls: List<String?> = listOf("Kotlin", null)
for (item in listWithNulls) {
    item?.let { println(it) } // prints A and ignores null
}


//elvis
val l = b?.length ?: -1

//early return
myVar ?: return

//for NPE-lovers
val l = b!!.length