could we always resolve `x += y` with `plusAssign`...
# stdlib
e
could we always resolve
x += y
with
plusAssign
and
x + y
with
plus
? It's really a pity to give up on that because of ambiguity
d
Because there're immutable objects. Like strings, for example. You can't use plusAssign for them.
e
?
k
Or another example,
Int
. What do you expect
a += 3
to do? Call
Int.plusAssign
? That doesn't exist, Ints are immutable.
That just needs to be compiled to
a = a + 3
.
e
I expect
a += 3
to be always translated to
a.plusAssign(3)
d
And what should
a.plusAssign(3)
do for
var a: Int
?
e
presents an error
d
looks like "not an option", doesn't it?
k
That's not how Kotlin/Java works. Let's say
a
is evaluated to 5, the actual call would then be
5.plusAssign(3)
. What is the "object"
5
supposed to do with this? It doesn't know about your variable
a
, and
5
itself is immutable.
e
I think of it really simple, if the class has the operator defined it will be overloaded
Int
doesnt
we have smart casting, wouldn't be possible to have something similar detecting the receiver type and act consequently?
it's really a blocker for me, in my glm lib I had to skip basically all the
*Assign
funcs for that
and replace with functional ones, such as
plus_
k
You could make all of your objects immutable.
e
not an option I'd say
d
How exactly is that a blocker for you? Currently, the rules are: (1) If there's a compound assignment operator (opAssign), then
a op= b
translates to
<get-a>().opAssign(b)
. (2) Otherwise,
a op= b
translates to
<set-a>(<get-a>().op(b))
. Compound assignment operator convention (case (1)) is there exactly for mutable objects. It can't work uniformly on JVM without additional allocations, and it is highly unlikely these rules would be changed. If you have mutable class C, and do not want to allocate new instances on compound operations, then you should define corresponding compound assignment operators. It could be possible to derive regular operators from compound assignment (feature request would be nice), not the other way around.
e
No sorry Dmitry, I misused the word blocker