Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: Iterable<T> from Sequence<T>

In Kotlin, how can I get an Iterable<T> from a Sequence<T> or from a Stream<T>?

In Java, I can get Iterable<T>s via the following methods, but the equivalent Kotlin code doesn't work:

final Stream<T> s = /*get Stream*/;
final Iterable<T> i1 = s::iterator;
final Iterable<T> i2 = () -> s.iterator();
like image 714
XDR Avatar asked Nov 24 '25 11:11

XDR


1 Answers

Since Kotlin has first-class function types, just providing a lambda or a method reference is not enough to coerce the expression into some Java interface. However, there is a concise syntax to implement a single-abstract-method interface:

val s: Stream<T> = /* get a stream */
val i = Iterable { s.iterator() }
like image 74
Marko Topolnik Avatar answered Nov 28 '25 02:11

Marko Topolnik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!