Skip to content

Support java collections & streams in for-do loops #15379

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions library/src/scala/runtime/stdLibPatches/Predef.scala
Original file line number Diff line number Diff line change
Expand Up @@ -60,4 +60,12 @@ object Predef:
inline def ne(inline y: AnyRef | Null): Boolean =
!(x eq y)

extension [T](it: java.lang.Iterable[T])
def foreach(f: java.util.function.Consumer[T]): Unit =
it.forEach(f)

extension [T](s: java.util.stream.Stream[T])
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we also support IntStream and the other primitive streams?

Copy link
Contributor

@TheElectronWill TheElectronWill Jun 10, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It we could support BaseStream (javadoc), which is the common interface above Stream, IntStream and all, it would be even better :)
edit: actually I got carried away: BaseStream doesn't provide any meaningful operation on its elements...

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it would be good to also support IntStream and the other primitive streams.

def foreach(f: java.util.function.Consumer[T]): Unit =
Copy link
Contributor

@odersky odersky Jun 15, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If it is in Predef then foreach needs to be inline, since stdLibPatches/Predef.scala has no runtime equivalent. Or else we need a PR against 2.13 Predef instead.

s.forEach(f)

end Predef
13 changes: 13 additions & 0 deletions tests/pos/java-collection-for-do.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import java.util.{List, ArrayList}
import java.util.stream.Stream

object JavaCollectionForDo {

for
x <- scala.List(1, 2, 3)
y <- List.of(1, 2, 3)
z <- Stream.of(1, 2, 3)
do
println(x + y + z)

}