Q:

How to convert a nested scala collection to a nested Java collection

I'm having compilation issues between Scala and Java.
My Java code needs a 
java.util.Map<Double, java.lang.Iterable<Foo>>

My scala code has a 
Map[Double, Vector[Foo]]

I get the compilation error:
error: type mismatch;
found   : scala.collection.immutable.Map[scala.Double,Vector[Foo]
required: java.util.Map[java.lang.Double,java.lang.Iterable[Foo]]

It seems the scala.collection.JavaConversions don't apply to nested collections, even though a Vector can be implictly converted to an Iterable.  Short of iterating through the scala collection and doing the conversion by hand, is there something I can do to make the types work?

A:

scala.collection.JavaConversions should be deprecated IMHO. You are better off being explicit about where and when the conversion happens by using scala.collection.JavaConverters. In your case:
import scala.collection.JavaConverters._

type Foo = Int // Just to make it compile
val scalaMap = Map(1.0 -> Vector(1, 2)) // As an example

val javaMap = scalaMap.map { 
  case (d, v) => d -> v.toIterable.asJava
}.asJava

A:

I wrote this general purpose function, which works well for my needs.
def toJava(x: Any): Any = {
  import scala.collection.JavaConverters._
  x match {
    case y: scala.collection.MapLike[_, _, _] => 
      y.map { case (d, v) => toJava(d) -> toJava(v) } asJava
    case y: scala.collection.SetLike[_,_] => 
      y map { item: Any => toJava(item) } asJava
    case y: Iterable[_] => 
      y.map { item: Any => toJava(item) } asJava
    case y: Iterator[_] => 
      toJava(y.toIterable)
    case _ => 
      x
  }
}

A:

This better suited my needs:
  def toJava(m: Any): Any = {
    import java.util
    import scala.collection.JavaConverters._
    m match {
      case sm: Map[_, _] => sm.map(kv => (kv._1, toJava(kv._2))).asJava
      case sl: Iterable[_] => new util.ArrayList(sl.map( toJava ).asJava.asInstanceOf[util.Collection[_]])
      case _ => m
    }
  }

