https://kotlinlang.org logo
#compiler
Title
# compiler
g

groostav

09/06/2023, 4:02 PM
regarding
for
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.
j

jw

09/06/2023, 4:03 PM
How would you support
break
?
🤦‍♂️ 1
g

groostav

09/06/2023, 4:05 PM
big oof. But pretending that I didnt completely forget about a really core old langauge feature:
inline fun
?
edit: dont need
inline
for break but I do need it for
return
.
e

ephemient

09/06/2023, 4:08 PM
there actually is a proposal for
for (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
)
🍻 1
g

groostav

09/06/2023, 6:33 PM
yeah @jw I think
break
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