Left Index

Null Saftey

In this article, we'll be looking at the null safety features built into the Kotlin language. Kotlin provides comprehensive, native handling of nullable fields.


By default at variable declaration, variable can not hold null value, we can create nullable object with help of '?'. For ex:

var name:String = "John Carlo";
name = null; // this will gives compiler error i.e. Null can not be a value of a non-null type String

println(name)

To allow a variable to hold null, we can declare a variable as nullable string, written String?, example:

var name:String? = "John Carlo";
name = null;

println(name)

Safe Call operator(?): Null Comparisons are simple but number of nested if-else expression could be burdensome. So, Kotlin has a Safe call operator, ?. that reduces this complexity and execute an action only when the specific reference holds a non-null value.. It allows us to combine a null-check and a method call in a single expression.

Example:
package com.theitbulls.kotlinex

fun main(args: Array<String>) {
	var name: String?
	name = null
	display(name)
}

fun display(name: String?) {
	println(name?.toUpperCase())
}

Is equivalent to:

Example:
package com.theitbulls.kotlinex

fun main(args: Array<String>) {
	var name: String?
	name = null
	display(name)
}

fun display(name: String?) {
	if(name != null) {
		println(name.toUpperCase())
	}
}

let() method: To execute an action only when a reference holds a non-nullable value, we can use a let operator. The lambda expression present inside the let is executed only if the variable empName is not null.

Example:
package com.theitbulls.kotlinex

fun main(args: Array<String>) {
	val empName: String? = "John Carlo"
	empName?.let { println(it) }
	
	// below code will print nothing, because studentName contains null
	val studentName: String? = null
	studentName?.let {println(it)}
}

run() method: Kotlin has a run() method to execute some operation on a nullable reference. It seems to be very similar to let() but inside of a function body, the run() method operates only when we use this reference instead of a function parameter:

Example:
package com.theitbulls.kotlinex

fun main(args: Array<String>) {
	val empName: String? = "John Carlo"
	empName?.run { println(empName) }
	
	// below code will print nothing, because studentName contains null
	val studentName: String? = null
	studentName?.run {println(studentName)}
}