Hi, is there an idiomatic way to attribute a value...
# getting-started
a
Hi, is there an idiomatic way to attribute a value to a variable if this variable is null ? Other than a
if
s
I guess
x = x ?: newValue
, but it feels a bit unintuitive
👍 1
j
How is this unintuitive? This is quite idiomatic for code written in Kotlin 🙂
👍 4
s
I just didn’t quite like the fact that it does the assignment even when x is not null. It’d feel nicer if there was a way to do it without assigning x to itself.
j
I can’t assure you this but I don’t think this is an issue since it’s probably optimized by the compiler
you can also just write
Copy code
if (x == null) x = newValue
it’s not that long
👍 3
j
It would be nice if we could do
x ?:= newValue
k
That would indeed be nice - it already exists in C#, as
??=
(since the C# has
??
as the equivalent of Kotlin's
?:
), called the "null-coalescing assignment operator".
a
Yup, there is the same thing in JavaScript
g
I think it is a questionable feature because it requires x to be mutable and it goes against Kotlin's direction to be immutable as much as possible. And
if
is simple and short enough already imo