Read the full article on DuraSoft, here: http://durasoftindia.com/blogposts/kotlin_null_safety_1.html
I was recently solving a programming problem listed in Advent of Code, using Kotlin programming language. After I finished the task, my friend glanced at the code and quipped, “Is question mark a first class citizen in Kotlin?”. I took a step back and looked at the code dispassionately and couldn’t stop smiling. Please take a look at this code snippet in Kotlin.
val tower = resultMap[code.trim()] tower?.occurences = value val weight:Int? = resultMap[code.trim()]?.weight nestedTower?.subTowers?.add(Tower(code.trim()))
You will notice a number of question mark ? operators used here. Kotlin, the new language on the JVM, is getting popular with null safety operators being one of the reasons. The question-mark(?) operator also known as the safe navigation operator is not entirely new to programming languages. It’s a commonly used one in languages like C#, Groovy etc., for a long time. Kotlin introduces this safety operator and extends it with a couple of more operators in the safety front.
To being with, let’s understand the difference between the two types of declarations in Kotlin shown below.
var anInt:Int = 10 var anotherInt:Int? = 20
Continued at the link above.