Hey guys, regaring inline classes: ```value class ...
# compiler
g
Hey guys, regaring inline classes:
Copy code
value class CoolZeroCostSequence(val arr: IntArray) { ...}
if i wanted to write
Copy code
val seq: CoolZeroCostSequence = makeArraySequenceThing()

for(int in seq){

}
and I wanted to avoid any boxing, which is to say, I do not want to create an instance of
Iterator<Int>
because that would box up my elements, how can I do it?
in my particular case I'm also wrapping the int:
Copy code
value class TraversalSequence(val array: IntArray){
  // want similar behaviour to Array<NodeEncounter> but actually IntArray
}
value class NodeEncounter(val idx: Int){
  val isLeave: Boolean get() = idx < 0
  val index: Int get() = idx.let { if(it > 0) it else -1*it }
}
from what I remember
for
needs an
operator fun iterator(): Iterator<Int>
, but that requres boxing... can i give you back an object with an
operator fun next()
on it instead?
f
You cannot avoid boxing when using generics AFAIK. So either you go the IntArray way (aka defining a separate class for each primitive, without inheriting from generics), or you go the list way (accept boxing). Wondering whether a compiler plugin could do this optimization behind the scenes...
y
There's a really easy way to do it with a custom Iterator implementation. Iterators in Kotlin don't have to implement
Iterator
interface, they only need to have
operator fun next()
and
operator fun hasNext(): Boolean
. So what you can do is something like this:
Copy code
class IntIterator(private val arr: IntArray, private var index: Int = 0) {
  operator fun next(): Int = arr[index++]
  operator fun hasNext(): Boolean = index < arr.length
}
operator fun CoolZeroCostSequence.iterator(): IntIterator = IntIterator(arr)
🍻 1
today i learned 1
g
does this type properly avoid boxing in a
for(elem in somethingThatsIntIterator)
?
y
The pre-existing Int iterator implements the Iterator interface, so I wasn't quite sure if it would be boxing or not, hence why I made my own. You can experiment with returning the pre-existing one and seeing what code is generated. I'm 100% sure that a custom one will not box, though.
e
it boxes if used generically but contains unboxed overloads that Kotlin can use: https://github.com/jetbrains/kotlin/pull/4753