Created
August 22, 2019 11:41
-
-
Save EmmanuelGuther/f9db48214cfbddbdc29e8532bee40f0c to your computer and use it in GitHub Desktop.
Kotlin elvis operator example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Elvis Operator | |
When we have a nullable reference r, we can say "if r is not null, use it, otherwise use some non-null value x": | |
val l: Int = if (b != null) b.length else -1 | |
Along with the complete if-expression, this can be expressed with the Elvis operator, written ?:: | |
val l = b?.length ?: -1 | |
If the expression to the left of ?: is not null, the elvis operator returns it, otherwise it returns the expression to the right. Note that the right-hand side expression is evaluated only if the left-hand side is null. | |
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") | |
// ... | |
} | |
fun foo(node: Node): String? { | |
val parent = node.getParent() ?: return null | |
val name = node.getName() ?: throw IllegalArgumentException("name expected") | |
// ... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment