i guess that's the real question: can i create an ...
# announcements
b
i guess that's the real question: can i create an inline class whose value can be modified in place to implement something like
inlineClassInstance++
to increment its value
k
b
oh! so does that mean it's taken care of it behind the scenes though?
(trying it out now in a scratch)
i saw the thing about 'val' and assumed it'd need to be modified so wouldn't work, but seemed like a big limitation on inline classes
k
Well in the end the operator
++
does behave as expected, it just always has to create a new instance, which for inline classes does't actually happen.
b
just tested it out and looks like it does work
awesome, thanks!
what about something like
plusAssign
?
k
plusAssign
is in-place, if you haven't implemented that it reverts to
plus
and assigning at the callsite, so "out-place". Full details on the page I linked earlier.
b
looks like it's just kinda magic with plus
ok yeah
it'd be impossible to implement plusAssign for an inline class, right?
k
Well the thing in the inline class can be mutable and you can mutate that, eg if it was a
MutableList
you could
add
to it.
b
oh ok, didn't know you could do an inline class with a more complex type like that
thanks for all the info @karelpeeters
k
You're welcome!
b
inline classes look like they'll solve an annoying problem i've had for a long time. excited to try them out.
k
What problem?
b
i need to model RTP sequence numbers which roll over at 2 bytes, so comparing and incrementing, etc. need to take that into account...but they're used a lot so never wanted the overhead of a full class
k
Problem is that you can't put any constraints on the stored value, but maybe that's not a problem for you?
b
hmm...that is a good point, but probably not a deal breaker as it's no worse than what we have now (just using an Int)
can i not throw in init with an invalid value?
k
There's no
init
for inline classes.
b
dang
k
Because you couldn't force Java code to call that init.
b
it'd be great to be able to validate, but since it's no worse than current implementation in that regard it's not too bad
h
You could make the constructor private and provide a "constructor overload" (function matching class constructor case) that would perform that validation instead.
k
No you can't make the constructor private for the same reason 🙂
h
You can with
@Suppress("NON_PUBLIC_PRIMARY_CONSTRUCTOR_OF_INLINE_CLASS")
k
Then you give up safety for Java interop, but that may be acceptable.
h
Yeah it obviously makes you unable to use
new
on the Java-side... but sometimes there is no Java-side
k
Even worse, if you take an inline class as an argument Java code could pass illegal "instances".
h
Isnt that possible in either case? At least way youd have some safety Kotlin side, and as I said sometimes Java interop isnt a concern anyways
k
Yeah you're right, this is a good idea in this case.
b
thanks @hudsonb i'll take a look at that!