Kotlin – Safe-call operator for Nullable types and let

Safe-call operator is an operator that Kotlin implemented so we can handle the Nullable types., <span>Kotlin – Safe-call operator for Nullable types and let</span>, KandZ

Safe-call operator is an operator that Kotlin implemented so we can handle the Nullable types. In Kotlin if a variable is nullable then you need to check if is null or not so you can access its properties.

var name:String? = "kronos"

    if (name != null){
        var length = name.length
        println(length)

    }

Safe-call operator (?.) returns the a value if not null otherwise it returns null. So we can rewrite the above code:

var name:String? = "kronos"
print(name?.length)
Safe-call operator is an operator that Kotlin implemented so we can handle the Nullable types., <span>Kotlin – Safe-call operator for Nullable types and let</span>, KandZ
not null
var name:String? = null
print(name?.length)
Safe-call operator is an operator that Kotlin implemented so we can handle the Nullable types., <span>Kotlin – Safe-call operator for Nullable types and let</span>, KandZ
null

You can also perform a specific operation when there is a non-null value using let

var name:String? = null
name?.let { println("I have ${name.length} letters") }
Safe-call operator is an operator that Kotlin implemented so we can handle the Nullable types., <span>Kotlin – Safe-call operator for Nullable types and let</span>, KandZ
value is null so prints nothing
var name:String? = "kronos"
name?.let { println("I have ${name.length} letters") }
Safe-call operator is an operator that Kotlin implemented so we can handle the Nullable types., <span>Kotlin – Safe-call operator for Nullable types and let</span>, KandZ
the value is not null so it prints.

THE END!!!

63350cookie-checkKotlin – Safe-call operator for Nullable types and letKotlin – Safe-call operator for Nullable types and let

Related posts

2 Thoughts to “Kotlin – Safe-call operator for Nullable types and let

  1. […] Kotlin – Safe-call operator for Nullable types and let […]

  2. […] Kotlin – Safe-call operator for Nullable types and let […]

Comments are closed.