How can I convert a Java Iterable to a Scala Iterable?

ScalaScala Java-Interop

Scala Problem Overview


Is there an easy way to convert a

java.lang.Iterable[_]

to a

Scala.Iterable[_]

?

Scala Solutions


Solution 1 - Scala

In Scala 2.8 this became much much easier, and there are two ways to achieve it. One that's sort of explicit (although it uses implicits):

import scala.collection.JavaConverters._

val myJavaIterable = someExpr()

val myScalaIterable = myJavaIterable.asScala

EDIT: Since I wrote this, the Scala community has arrived at a broad consensus that JavaConverters is good, and JavaConversions is bad, because of the potential for spooky-action-at-a-distance. So don't use JavaConversions at all!


And one that's more like an implicit implicit: :)

import scala.collection.JavaConversions._

val myJavaIterable = someExpr()

for (magicValue <- myJavaIterable) yield doStuffWith(magicValue)

Solution 2 - Scala

Yes use implicit conversions:

import java.lang.{Iterable => JavaItb}
import java.util.{Iterator => JavaItr}

implicit def jitb2sitb[T](jit: JavaItb[T]): Iterable[T] = new SJIterable(jit);
implicit def jitr2sitr[A](jit: JavaItr[A]): Iterator[A] = new SJIterator(jit)

Which can then be easily implemented:

class SJIterable[T](private val jitb: JavaItr[T]) extends Iterable[T] {
  def elements(): Iterator[T] = jitb.iterator()
}

class SJIterator[T](private val jit: JavaItr[T]) extends Iterator[T] {
  def hasNext: Boolean = jit hasNext

  def next: T = jit next
}

Solution 3 - Scala

Starting Scala 2.13, package scala.jdk.CollectionConverters replaces deprecated packages scala.collection.JavaConverters/JavaConversions:

import scala.jdk.CollectionConverters._

// val javaIterable: java.lang.Iterable[Int] = Iterable(1, 2, 3).asJava
javaIterable.asScala
// Iterable[Int] = List(1, 2, 3)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatt RView Question on Stackoverflow
Solution 1 - ScalaAlex CruiseView Answer on Stackoverflow
Solution 2 - Scalaoxbow_lakesView Answer on Stackoverflow
Solution 3 - ScalaXavier GuihotView Answer on Stackoverflow