Search code examples
scalacollectionsscala-collectionsgeneric-collectionsscala-java-interop

Use java.util.Map from Scala


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?


Solution

  • 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'