Skip to main content

Posts

Showing posts with the label kotlin null safety

Kotlin elvis operator ?:

?: Symbol for elvis operator is ?: The elvis operator couples with safe call operator ?. Elvis operator returns the value to it's left if value is not null, else it returns the value to it's right var foo = a ?: b Here, if a is null, b is returned. If a is not null, a is returned. Another elaborate example: var msg: String? msg = null // use elvis operator var msgLength1 = msg?.length ?: 0 // use traditional null check var msgLength2: Int if (msg != null) { msgLength2 = msg.length } else { msgLength2 = 0 } println(msgLength1) // 0 println(msgLength2) // 0 In above code snippet, calculate of msgLength1 using safe call operator and elvis operator is same as calculation of msgLength2 using traditional conditional check.

Kotlin: safe call operator ?.

?. What does the safe call operator do? Symbol for safe call operator is ?. It safely calls function or accesses property of a nullable object Returns null in case the object has null value, else calls the function or accesses property. Safe call operator can be chained and returns null if any of the object in chain. var msg: String? msg = null println(msg?.length) // prints "null" // here msg?. returns null since msg is null, // instead of accessing the .length property Chaining safe call operator println(foo?.bar?.baz?.someProp) This chain would return null if either of foo, bar or baz have null value but won't check someProp for null value!

Null safety in Kotlin

Kotlin is designed to be null safe! A null pointer exception occurs when we try to use variables that have null value. Kotlin is designed in such a way that it greatly reduces the possibility of null pointer exceptions. Variables in Kotlin can not hold a null value by default Nullable variable i.e. variables that can hold null values, needs to be explicitly defined so. Let's understand a few null safety concepts in Kotlin with these simple code snippets. Remember, how to define variables? We are going to go ahead and define a variable and try to assign null value to it. var msg: String msg = null This isn't allowed in kotlin since we didn't explicitly specify that the variable msg can contain null value. If you try to run the program, you will get an error. But sometimes, we need a variable to have null value now and then some other value later. Adding a question mark at the end of variable definition allows us to explicitly declare that this variable may c...