I got confused with the following Kotlin expression

val s = person.name ?: return

      

I know what is ?

used for null security ... but what does :return

.

+3


source to share


2 answers


?:

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.

+8


source


?:

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`

      

+2


source







All Articles