quick, simple proposal
# language-proposals
e
quick, simple proposal
🚫 10
🤔 5
👌 1
2
m
What are the situations where you’d use that? In years of Kotlin I’ve never even needed the current form
x = x ?: y
🤔
e
You've never done anything along the lines of
if(x == null) x = y
or the JavaScript pattern
x = x || y
?
Ruby has
||=
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.
m
I’ve never like the JavaScript pattern. The problem with it is that it has a different meaning than
if (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.
e
Ignoring JavaScript, Ruby's
||=
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?
Ignoring usefulness now, I'm just curious why you are saying (I think) that it can't work at all.
m
I’m not saying that it can’t work. I’m saying that
if (x === null) x = y
and
x = x ?: y
do different things. The latter translates to
Copy code
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.
l
i strongly dislike this as it would encourage having x be mutable for no good reason.