Kotlin – Elvis and NPE operator

Elvis and NPE operator, <span>Kotlin – Elvis and NPE operator</span>, KandZ

Elvis operator ?:

In Kotlin the Elvis operator ?: is a binary operator that returns its first operand if that operand is true, and otherwise evaluates and returns the second operand. It is not important the first operand to have the literal value true so the first operand could be returned. It just needs to be a value that is considered to true. You can say that the Elvis operator ?: is a variant of the ternary conditional operator.

    val name: String? = "kronos"
    val nameStatus: String = name ?: "empty"
    println(nameStatus)

    val lastName: String? = null
    val lasmnameStatus: String = name ?: "empty"
    println(lastName)
Elvis and NPE operator, <span>Kotlin – Elvis and NPE operator</span>, KandZ

not-null assertion operator !!

This operator tells the compiler that if it is null throw a null pointer exception (NPE) . It converts any value to a non-null type.

    val name: String? = "kronos"
    println(name!!)

    val lastName: String? = null
    println(lastName!!)
Elvis and NPE operator, <span>Kotlin – Elvis and NPE operator</span>, KandZ
as you see it threw an null pointer exception for the last name

63710cookie-checkKotlin – Elvis and NPE operatorKotlin – Elvis and NPE operator

Related posts

One Thought to “Kotlin – Elvis and NPE operator

Comments are closed.