views:

1080

answers:

2

I'm trying to convert a project over to scala 2.8 from 2.7 and I've run into some difficulty in the code that interacts with Java. Below is a slightly convoluted piece of sample code displaying the problem. Essentially I have class with a member variable of type mutable.Map[K,V] and I can't find a way to pass that through to a method that expects a java.util.Map[K,V]. Any help would be great.

scala> import scala.collection.JavaConversions._
import scala.collection.JavaConversions._

scala> class A[K,V](m : collection.mutable.Map[K,V]) { 
     | def asJava : java.util.Map[K,V] = m
     | }

<console>:9: error: could not find implicit value for parameter ma: scala.reflect.ClassManifest[K]
       def asJava : java.util.Map[K,V] = m
+5  A: 

I don't know why you are trying to repeat the conversion from JavaConversions, but i think you can do it with adding the implicit parameter ma requested:

import scala.collection.JavaConversions._
class A[K,V](m : collection.mutable.Map[K,V]) {
 def asJava(implicit ma:ClassManifest[K]) : java.util.Map[K,V] = m
}

From console

scala> import scala.collection.JavaConversions._
class A[K,V](m : collection.mutable.Map[K,V]) {
 def asJava(implicit ma:ClassManifest[K]) : java.util.Map[K,V] = m
}
import scala.collection.JavaConversions._

scala>
defined class A

scala> val map=scala.collection.mutable.HashMap[Int, Int]()
map: scala.collection.mutable.HashMap[Int,Int] = Map()

scala> map += 0->1
res3: map.type = Map(0 -> 1)

scala> val a=new A(map)
a: A[Int,Int] = A@761635

scala> a.asJava
res4: java.util.Map[Int,Int] = {0=1}
Patrick
Thanks Patrick. That worked perfectly. I'm not trying to repeat the conversions, that example was just the easiest way to show the problem I was having.
Dave
+5  A: 

Easily solvable:

class A[K : ClassManifest,V](m : collection.mutable.Map[K,V]) {
  def asJava : java.util.Map[K,V] = m
}

Though, as mentioned, it begs the question as to why you are bothering to replicate this method, which you could call directly from JavaConversions, or even use it implicitly. You might have good reasons for it, of course, or you might have done it just to get around how conversions worked on Scala 2.7.

Daniel
Clever as usual +1
Patrick