Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use multiple line in Elvis operator in kotlin

Tags:

android

kotlin

I have this code in Android Studio:

    val newUser = !intent.hasExtra("newUser")
    val userData = intent.getParcelableExtra("newUser") ?: UserData()

There is a problem in this code. if an extra that isn't UserData exists in intent and if its key is "newUser", newUser becomes false but userData becomes a new instance of UserData. I am looking for something like this:

val userData = intent.getParcelableExtra("newUser") ?: {
    newUser = true
    UserData()
}

I konw this code doesn't work but is there a way to do it?

like image 295
mohammad Avatar asked Mar 01 '18 19:03

mohammad


People also ask

What does ?: Mean in Kotlin?

In certain computer programming languages, the Elvis operator ?: is a binary operator that returns its first operand if that operand is true , and otherwise evaluates and returns its second operand.

How does Elvis operator work?

What is the Elvis operator? The Elvis operator in Kotlin is an operator that receives two inputs and returns the first argument if it is non-null or the second one otherwise. It is fancily called the null-coalescing operator. It is a variant of the ternary operator but for null-safety checking.


1 Answers

You can wrap the block in the run function:

val userData = intent.getParcelableExtra("newUser") ?: run {
    newUser = true
    UserData() 
}
like image 102
yole Avatar answered Sep 22 '22 05:09

yole