1

I have a Scala data structure created with the following:

List(Map[String, Anyref]("a" -> someFoo, "b" -> someBar))

I would like to implicitly convert it (using scala.collection.JavaConversions or scala.collection.JavaConverters) to a java.util.List<java.util.Map<String, Object>> to be passed the a Java method that expects the latter.

Is this possible?

I have already created the following method that does it, but was wondering if it can be done automatically by the compiler?

import scala.collection.JavaConversions._
def convertToJava(listOfMaps: List[Map[String, AnyRef]]):
  java.util.List[java.util.Map[String, Object]] = {
  asJavaList(listOfMaps.map(asJavaMap(_)))
}

2 Answers 2

4

How about writing

implicit def convertToJava...

?

Sign up to request clarification or add additional context in comments.

2 Comments

That makes sense, but I was hoping that Scala would do it automatically so I could save 4 lines of code :-).
This is a quite special case, so I think these 4 lines are okay. Generally over-the-top use of implicit conversion can lead to surprising results, so it's only sensible that the Scala library uses them with caution.
4

You don't want this kind of multilevel conversion happening by magic. You can improve a little on your own conversion though, at least aesthetically.

import java.{ util => ju }
implicit def convert[K, V](xs: List[Map[K, V]]): ju.List[ju.Map[K, V]] = xs map (x => x: ju.Map[K, V])

3 Comments

I'm giving you an upvote just for the import aliasing line - didn't know one could do that!
Thanks. I'll take a look at your solution.
@Esko: I've started using the import aliasing to rename java.* classes: import java.lang.{Integer => JInteger} for those rare cases where I have to force autoboxing: (x: JInteger).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.