Paul Draper
Paul Draper

Reputation: 83245

Scala equivalent of java.util.stream

Is there an Scala type (probably a trait) similar to java.util.stream.Stream?

(I am using the better-supported Java 7, so Java 8's Stream is not available to me.)

Specifically, it must be generically typed, be iterable in some way, and be closeable.

try {
  stream.foreach(println)
  }
} finally {
  stream.close()
}

A solution in the standard libraries would be preferred, though something in another library would be acceptable.

Upvotes: 4

Views: 1329

Answers (1)

Alexandru Nedelcu
Alexandru Nedelcu

Reputation: 8069

For collections, all collections in Scala can be used as if they are streams. In Scala the operators on Iterable / Iterator are lazily applied for example and you also have Views and Stream (Stream is a lazily evaluated List and does memoization of the traversed values, so if you want memoization you can use a stream, but because of the memory requirements this it tricky for working with infinite streams - still it's pretty cool).

As you might have noticed however, this doesn't take care of all cases, because the stream could be a stream of data coming from a network socket, file handle and so on. So one needs to dispose of the underlying resources used.

I do not know of a direct equivalent, however I must also mention that I do not like Java's streams, because Java's streams are for processing iterable sequences, which means that their current design is pull-based. This may change in the future, but when processing streams, especially streams involving I/O, it's better to go non-blocking and asynchronous, therefore I prefer push based approaches, like Iteratees, or the Reactive Extensions (Rx) pattern.

A lot is going on in the Scala/Java ecosystem in this regard. There is RxJava, which is an Rx.NET port. There's also Akka Streams, part of the Reactive Streams effort to specify an interoperable protocol for back-pressure - in the experimental/alpha stage.

And a shameless promotion - I'm working on Monifu, an Rx implementation for Scala, that does back-pressure and that will also be integrated with the "Reactive Streams" protocol. And I also think it's already in a better shape and more idiomatic than the RxScala adaptor of RxJava, but since I'm the author, take that with a grain of salt :-)

Upvotes: 4

Related Questions