Use java.util.Map from Scala

7.3k views Asked by At

I need to use java-legacy code with the following method:

public void doit(Map <String, Object> vals) {...}

My Scala code:

var map = new java.util.HashMap[String, Any]
map += "testme" -> 'X'
doit(map)

yields =>

type mismatch; found : java.util.HashMap[String, Any] required: java.util.HashMap[java.lang.String, java.Object]

So I change it to:

var map = new java.util.HashMap[java.lang.String, Object]
map += "testme" -> 'X'
doit(map)

yields =>

type mismatch; found : Char required: java.lang.Object Note: primitive types are not implicitly converted to AnyRef. You can safely force boxing by casting x.asInstanceOf[AnyRef].

So finally I came up with the following:

var map = new java.util.HashMap[java.lang.String, Object]
map += "testme" -> 'X'.asInstanceOf[AnyRef]
doit(map)

Is there is a more concise way to deal with this?

3

There are 3 answers

0
Rex Kerr On BEST ANSWER

There's not a built in method to make it shorter, but you can write a helper method:

def jkv(s: String, a: Any) = s -> a.asInstanceOf[AnyRef]

map += jkv("testme",'X')

or use the pimp-my-library pattern to add a new operator that does this for you

class StringArrow(s: String) {
  def ~>(a: Any) = s -> a.asInstanceOf[AnyRef]
}
implicit def string_has_arrow(s: String) = new StringArrow(s)

map += "testme" ~> 'X'
0
Nikita Skvortsov On
  1. Maybe you could use come implicit conversions from scala.collection.JavaConversions._ It will allow you to scala mutable or immutable maps instead of java.util.HashMap

  2. I do not know the context, but maybe you could use "testme" -> "X" (with String)

0
Ken Bloom On

Use type ascription as follows:

import java.lang.Character

var map = new java.util.HashMap[java.lang.String, Object]
map += "testme" -> ('X':Character)
doit(map)

This tells Scala that you want the 'X' to be implicitly converted to java.lang.Character if it isn't one already. (It works becuase it specifies a more specific type than Object)