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?
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.
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.
You can wrap the block in the run
function:
val userData = intent.getParcelableExtra("newUser") ?: run {
newUser = true
UserData()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With