https://kotlinlang.org logo
#stdlib
Title
# stdlib
t

Thomas

03/19/2024, 1:50 AM
What's the reason behind making `Iterable`'s only constructor a higher order function with an
Iterator
producer, instead of a simple function that takes a single
Iterator
?
Code in question (Kotlin 1.9.21):
Copy code
/**
 * Given an [iterator] function constructs an [Iterable] instance that returns values through the [Iterator]
 * provided by that function.
 * @sample samples.collections.Iterables.Building.iterable
 */
@kotlin.internal.InlineOnly
public inline fun <T> Iterable(crossinline iterator: () -> Iterator<T>): Iterable<T> = object : Iterable<T> {
    override fun iterator(): Iterator<T> = iterator()
}
Why isn't it simpler, like:
Copy code
public fun <T> Iterable(iterator: Iterator<T>): Iterable<T> = object : Iterable<T> {
    override fun iterator(): Iterator<T> = iterator
}
oh and to be fair I probably shouldn't call it a constructor 👀
j

jw

03/19/2024, 2:13 AM
Iterators are one-shot. Iterables are many-shot.
👌 2
t

Thomas

03/19/2024, 2:14 AM
ah right that makes sense, thanks