tags:

views:

559

answers:

1

Is there an easy way to convert a

java.lang.Iterable[_]

to a

Scala.Iterable[_]

?

+4  A: 

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 Siterator[T](private val jit: JavaItr[T]) extends Iterator[T] {
  def hasNext: Boolean = jit hasNext

  def next: T = jit next
}
oxbow_lakes
Thanks, I was hoping there was something like this in the standard Scala libs, but as you've shown, it's not too hard to roll your own.
Matt R
It's ridiculous thinking how much code this would have been the other way around!
oxbow_lakes
This will be in the standard library starting with Scala 2.8.
Jorge Ortiz