I got confused with the following Kotlin expression
?:
called Elvis Operator .
val s = person.name ?: return
equally:
val s = if (person.name != null) person.name else return
which means if person.name
there is null
, return.
source to share
?:
returns the expression on the right side in case its left expression null
.
In this case, instead of giving a s
value, it will return immediately from the current function. You can also throw an exception in a similar way if there is something null
and you don't have a good way to continue what you intend to do with it.
This example is mostly shorthand for the following (assuming a name String?
):
val s: String? = person.name
if(s == null) {
return
}
// you can use `s` here as it will be smart cast to `String`
source to share