Reputation: 4267
Is it possible to conditional assign a value in one line in kotlin?
Setup
var foo: String
if (x != 0) {
foo = x
}
Goal
// nothing is set if condition is false
foo = if (x != 0) x
Not wanted
// null is set if condition is false
foo = takeIf{ x != 0 }.let{ x }
Upvotes: 4
Views: 9180
Reputation: 37680
The usual way of doing this would be the following:
if (x != 0) foo = x
This is not always possible, because smart casting cannot be performed if there is a chance that another thread modifies the value between the null check in the assignment. This happens for instance if your x
is a nullable var
property on the class.
In that case, you have this option:
x?.let { foo = it }
Upvotes: 3
Reputation: 5214
Is
foo = if (x != 0) x else foo
you want?
(Besides, you declared var foo: String
, and the x != 0
may indicate a x: Int
, then you are not able to foo = x
. Maybe a typo here.)
Upvotes: 11