?:
- 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.
Comments
Post a Comment