eduardog3000
12/29/2019, 12:53 AMMarc Knaup
12/30/2019, 11:03 AMx = x ?: y
🤔eduardog3000
12/30/2019, 9:58 PMif(x == null) x = y
or the JavaScript pattern x = x || y
?eduardog3000
12/30/2019, 9:59 PM||=
which is about the same as this idea. It's ultimately the same as x || x = y
, so if x isn't nil it skips the assignment operator entirely. Kotlin could ultimately optimize this down to if(x == null) x = y
, or something else more efficient.Marc Knaup
12/31/2019, 7:39 AMif (x === null) x = something
.
If x
is a property or has a delegate, there may be a setter behind it which is triggered by the re-assignment of the variable to itself, which can cause unexpected side-effects.
For the same reason you cannot automatically convert that pattern to the if
form because the semantics are different.eduardog3000
01/03/2020, 9:28 PM||=
solves your problem by being equivalent to x || x = y
.
I'm not understanding how the last paragraph connects? Why couldn't ?=
be equivalent to if(x == null) x = y
in Kotlin, which means in reality that = still might be calling a setter, but only if x is null?eduardog3000
01/03/2020, 9:29 PMMarc Knaup
01/04/2020, 5:59 AMif (x === null) x = y
and x = x ?: y
do different things.
The latter translates to
if (x === null)
x = y
else
x = x
And the last statement here, x = x
can cause side-effects if it is a property with a setter or a has a delegate. Both may executes additional code due to re-assignment of the same value.Leon K
02/14/2020, 1:44 PM