Skip to content

Instantly share code, notes, and snippets.

@diversit
Created January 15, 2016 13:43
Show Gist options
  • Save diversit/bc028383a2c4c93cf601 to your computer and use it in GitHub Desktop.
Save diversit/bc028383a2c4c93cf601 to your computer and use it in GitHub Desktop.
Implicit conversion of a Java8 Stream into a Scala Stream
/**
* Since using a Java8 Stream in Scala is not easy since Scala functions do not map to Java8 functions (yet, is experimental).
* While apparently using lambda's in other parts like Swing callbacks is possible, defining a java.util.function.Function[A,B]
* in Scala code does not work. Compiler keeps complaining:
* {{{
Error:(52, 10) no type parameters for method map: (x$1: java.util.function.Function[_ >: A, _ <: R])java.util.stream.Stream[R] exist so that it can be applied to arguments (java.util.function.Function[A,B])
--- because ---
argument expression's type is not compatible with formal parameter type;
found : java.util.function.Function[A,B]
required: java.util.function.Function[_ >: A, _ <: ?R]
}}}
* <p>
* Converting the Java8 stream into Scala solves this issue since then we can just use Scala functions
* (which we do want anyway :-)
*/
implicit class JavaStreamToScalaStream[T](val stream: java.util.stream.Stream[T]) {
def asScala: scala.collection.immutable.Stream[T] = Try {
def next(it: java.util.Iterator[T]): Stream[T] = if (it.hasNext) { it.next() #:: next(it) } else scala.collection.immutable.Stream.empty[T]
next(stream.iterator())
}.recover {
case error =>
// Might occur when trying to consume the Java stream twice using 'asScala' method.
// Add some logging?
Stream.empty[T]
}.get
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment