Other concepts in Safe call operator

To perform a certain operation only for non-null values, you can use the safe call operator together with let

val listWithNulls: List<String?> = listOf("Kotlin", null)

for (item in listWithNulls) {

    item?.let { println(it) } // prints Kotlin and ignores null

}


A safe call can also be placed on the left side of an assignment. Then, if one of the receivers in the safe calls chain is null, the assignment is skipped, and the expression on the right is not evaluated at all:

// If either `person` or `person.department` is null, the function is not called: 
person?.department?.head = managersPool.getManager()



For more safe call operator details


Comments

Popular Posts