Linux Format

Null safety

-

In the Kotlin tutorial of the previous LinuxForma­t issue, we mentioned the term Null safety. Now it’s time to learn more about this important Kotlin characteri­stic, which makes your code easier to read and much safer. First, look at the following example of Kotlin code: var aString = “Tsoukalos” aString = null This code won’t compile because the default Kotlin behaviour doesn’t permit you to assign a null value to a variable. The generated error message will be null can not be a value of a nonnull type String , which shows exactly what’s

going on. However, you can change that behaviour with the use of the safe null access operator, which is a question mark: >>> var anotherStr­ing: String? = “Tsoukalos” >>> anotherStr­ing = null

Kotlin goes a step further and requires you to check a variable that can be null before using it. Bearing this in mind, we know that the following Kotlin program won’t compile: fun printA(printMe: String) { println(printMe) }

fun main(args: Array<String>) { val a: String? = “Tsoukalos” printA(a) }

However, if you replace printA(a) with the following snippet of code, then the nSafety.kt program will compile just fine: if (a != null) printA(a)

If you’re an amateur programmer, you might not immediatel­y appreciate the null safety feature of Kotlin, but it does save you from NullPointe­rException­s… and this is a great thing!

Newspapers in English

Newspapers from Australia