https://kotlinlang.org logo
#getting-started
Title
# getting-started
r

Ray Rahke

02/23/2024, 9:00 PM
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

ephemient

02/23/2024, 9:03 PM
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

Ray Rahke

02/23/2024, 9:05 PM
fun inc()
you mean `clock.inc()`` ?
so no overload
e

ephemient

02/23/2024, 9:05 PM
yeah as a member function (or possibly an extension fun)
correct
r

Ray Rahke

02/23/2024, 9:06 PM
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

ephemient

02/23/2024, 9:07 PM
depends on what's in scope
r

Ray Rahke

02/23/2024, 9:07 PM
i assumed set += was equivalent to set.add()
e

ephemient

02/23/2024, 9:08 PM
Copy code
val x = mutableSetOf<Int>()
x += 1 // x.plusAssign(1)

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