Scala 2.8 Import java conversions

I am trying to convert a project to scala 2.8 from 2.7, and I ran into some difficulties in code that interacts with Java. The following is a slightly confusing piece of sample code showing the problem. Essentially, I have a class with a member variable of type mutable.Map[K,V], and I cannot find a way to pass this before the method that expects 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
+3
source share
2 answers

I don’t know why you are trying to repeat the conversion from JavaConversions, but I think you can do this with the addition of an implicit parameter ma:

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}
+5
source

:

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

, , , , JavaConversions, . , , , , Scala 2.7.

+5

Source: https://habr.com/ru/post/1730524/


All Articles