I have two Java classes: LogEntry and Record.
The LogEntry class has a method shown below:
public LogEntry setRec(List<Map<String,List<Record>>> rec)
In Scala I try to put Record into LogEntry like this:
import scala.collection.JavaConversions._
import collection.mutable._
val log = new LogEntry()
val rec = new Record()
val map:java.util.Map[String, java.util.List[Record]] = HashMap("sessionKey" -> ArrayBuffer(rec))
log.setRec(List(map))
But I got a compile error:
scala> val map:java.util.Map[String, java.util.List[Record]] = HashMap("sessionKey" -> ArrayBuffer(eventPart))
<console>:14: error: type mismatch;
found : scala.collection.mutable.HashMap[String,scala.collection.mutable.ArrayBuffer[Record]]
required: java.util.Map[String,java.util.List[Record]]
val map:java.util.Map[String, java.util.List[Record]] = HashMap("sessionKey" -> ArrayBuffer(eventPart))
^
Seems that the auto convention from Scala collection to Java collection failed, but as described in the official doc :
mutable.Buffer <=> java.util.List
mutable.Map <=> java.util.Map
scala> val jul: java.util.List[Int] = ArrayBuffer(1, 2, 3)
jul: java.util.List[Int] = [1, 2, 3]
scala> val m: java.util.Map[String, Int] = HashMap("abc" -> 1, "hello" -> 2)
m: java.util.Map[String,Int] = {hello=2, abc=1}
ArrayBuffer can be convert to java.util.List and HashMap can be convert to java.util.Map.
So, why this error occurred?
The implicit conversions don’t apply to type parameters (though you can use view bounds to simulate it). That is, if you have implicit conversion from
FootoBar, values of typeFoocan be used whereBaris needed:but (e.g.)
Seq[Foo]can’t be used instead ofSeq[Bar]:That’s why conversion between
ArrayBufferandjava.util.Listcan’t be used there.