groostav
09/06/2023, 4:02 PMfor
statements and the compilers ability to convert non-Iterable
types into foreach loops: has kotlin considered simply allowing an operator fun forEach(block: YourType -> Unit)
to let you for(a in A)
through something?
This seems most useful to me in the case of `value class`'s, where your looking to avoid overhead for one reason or another.
In my case I'm trying to encode something to a type akin to a value class MyInlineCollection: Collection<MyInlineValue>
but I was hoping to avoid the boxing & unboxing `Iterator`'s next(): T
implementation.
Kotlin has my back: it doesn't need an Iterator
per say, it just needs an operator fun iterable(): Something
that returns something that has functions next()
and hasNext()
(available statically) on them.
But why not make kotlinc's life simpler: why doesn't it simply require me to supply it with an operator fun foreach(block: (MyValueType) -> Unit)
?
wins:
• kotlinc's life is a little easier in that it no longer has to check for signatures on methods of a statically returnned type (and all the denotable class nonsense that goes with it)
• I get to save an object allocation and dont have to write a state machine into an object anymore
Everybody wins?
Backward compatibility is saved by the requirement to put an operator
on the function, which is currently illegal, so introducing this as a change doesn't break anybody.
Overloads get pretty messy. You would have to be pretty explicit (and require some checkers) to make it clear whether iterator
or foreach
will be called.
And I suppose ZGC is so fast that it renders the removal of one Iterator object per foreach loop a pretty worthless optimization.jw
09/06/2023, 4:03 PMbreak
?groostav
09/06/2023, 4:05 PMinline fun
?inline
for break but I do need it for return
.ephemient
09/06/2023, 4:08 PMfor (x in a) ...
to desugar to `a.forEachWhile { x -> ...`: https://youtrack.jetbrains.com/issue/KT-33851 (where `break`/`continue` can be simulated with a local return false/true
)groostav
09/06/2023, 6:33 PMbreak
and continue
both seem fine (they map intuitively to block.invoke()
returning and forEach{}
returning respectively), the issue would be a return
issued out of the body for the for
. https://youtrack.jetbrains.com/issue/KT-33851/iterator-less-for-statement-operator-convention#focus=Comments-27-8067051.0-0