I have a clock class and I think it would look nic...
# getting-started
r
I have a clock class and I think it would look nice to overload the
++
to call it's tick() method, like
clock++
. However it looks like Kotlin says that the inc operator overload needs to return a new copy of the object, instead of mutate? Why? Is that how this behavior always works? I just want to mutate the clock's internal .now/.elapsed/.delta etc. Returning a new copy of the clock seems wasteful as I am going to call this function hundreds of times every few seconds
e
you can think of
x++
as
Copy code
val tmp = x
x = x.inc()
tmp
and
++x
as
Copy code
x = x.inc()
x
the prefix and postfix forms aren't defined independently as they are in C++
since the expression
x++
evaluates to the previous value of
x
, it isn't something that can easily be done by mutating in-place
in your case, I'd just use a non-operator
fun inc()
for in-place mutation
r
fun inc()
you mean `clock.inc()`` ?
so no overload
e
yeah as a member function (or possibly an extension fun)
correct
r
alright well what about things I make that function as collections of stuff
I have a player.inventory that just wraps over a mutable set
so an Inventory class
I would like to be able to do player.inventory += sword
just as I can do with the native set
mutableSetOf() += sword
is it creating a copy when I do it with the native sets?
or is it mutating
e
depends on what's in scope
r
i assumed set += was equivalent to set.add()
e
Copy code
val x = mutableSetOf<Int>()
x += 1 // x.plusAssign(1)

var x = setOf<Int>()
x += 1 // x = x + 1 // x = x.plus(1)