The Elvis Operator (?:) is represented by a question mark followed by a colon: ?: .It is ?: is a binary operator. If the first operand is not null, it is returned. Otherwise the value of the second operand (which may be null) is returned and it can be used with this syntax:
Lets take example:
If the expression to the left of ?: (here : b?.length) is not null, the elvis operator returns it (here: result of expression b.length), otherwise it returns the expression to the right (here: -1). Note that the right-hand side expression is evaluated only if the left-hand side is null.
Things to Note
Note that, since throw and return are expressions in Kotlin, they can also be used on the right hand side of the elvis operator. This can be very handy, for example, for checking function arguments:
fun foo(node: Node): String? {
val parent = node.getParent() ?: return null
val name = node.getName() ?: throw IllegalArgumentException("name expected")
// ...
}
first operand ?: second operand
Lets take example:
If the expression to the left of ?: (here : b?.length) is not null, the elvis operator returns it (here: result of expression b.length), otherwise it returns the expression to the right (here: -1). Note that the right-hand side expression is evaluated only if the left-hand side is null.
var b: String? = "Some Nullable String Value"
val l = b?.length ?: -1
val l = b?.length ?: -1
When we have a nullable reference r, we can say "if r is not null, use it, otherwise use some non-null value x"
Above Elvis operator expression written with ?:: can be expressed along with the complete if-expression as below:
val l: Int = if (b != null) b.length else -1
Things to Note
Note that, since throw and return are expressions in Kotlin, they can also be used on the right hand side of the elvis operator. This can be very handy, for example, for checking function arguments:
fun foo(node: Node): String? {
val parent = node.getParent() ?: return null
val name = node.getName() ?: throw IllegalArgumentException("name expected")
// ...
}
No comments:
Post a Comment