Is there a way to create an anonymous inline/value...
# language-evolution
k
Is there a way to create an anonymous inline/value object? Use case in 🧵.
I have a use case for a local variable that must always be incremented every time it is accessed. I thought about making it a value class:
Copy code
@JvmInline
value class SelfIncrementingLong(private var value: Long) {
    fun getAndIncrement() = value++
}
...
val offset = SelfIncrementingLong(0)
Now the only way I can get the value is using getAndIncrement. This need is very specific and local to this function, so I didn't want to create a new class for it. It's much more concise to use an anonymous class:
Copy code
val offset = object {
    private var value: Long = 0
    fun getAndIncrement() = value++
}
But now offset is boxed. Is it possible to write an anonymous object but have it as a @JvmInline value class? If not, is there an existing proposal for such a thing?
y
local value classes seem to be explicitly forbidden right now, so that'd include anonymous value classes as well.
Btw, you might wanna add an
inline fun SelfIncrementingLong.getValue
which calls
getAndIncrement
Oh and also, your code doesn't even compile right now because value classes must have a val, not a var. I think sadly you'll have to wait until copying functions come into the language
thank you color 1
k
Thanks. What would be the advantage of an
inline fun SelfIncrementingLong.getValue
?
y
So you'd just do
val offset by SelfIncrementingLong(0)
and every time
offset
is used, the long would be incremented
👍 1