mohammad
mohammad

Reputation: 1318

Use multiple line in Elvis operator in 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?

Upvotes: 25

Views: 5859

Answers (1)

yole
yole

Reputation: 97168

You can wrap the block in the run function:

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

Upvotes: 56

Related Questions