https://kotlinlang.org logo
Title
s

streetsofboston

02/15/2019, 5:56 PM
Kotlin has more constructs that are expressions than Java has (e.g.
if
,
when
,
try
expressions in Kotlin, but not in Java). What was the reason that the assignment operator
=
is not an expression?
i

ilya.gorbunov

02/15/2019, 6:04 PM
Mainly because
=
is used in named arguments syntax:
foo(arg = value)
This is a call of
foo
with
arg
argument, rather than a call of
foo
with the result of assignment of
value
to some
arg
variable/property.
👍 4
s

streetsofboston

02/15/2019, 6:15 PM
Ah! Thank you! I thought it was done to discourage coding expressions with side-effects. But then I realized that
(value++)
would exactly be such an expression 🙂
g

ghedeon

02/15/2019, 6:26 PM
It also prevents accidental mistakes when == is intendet, right?
k

karelpeeters

02/15/2019, 7:08 PM
@ghedeon How often does that happen? It would only compile for a boolean and you never do
== true
anyway. You can compare two booleans but that's even more rare.
i

ilya.gorbunov

02/15/2019, 9:59 PM
Note that you can achieve the same effect as assignment expression with
also
function:
foo(value.also { someVar = it })