开发者

Use java.util.Map from Scala

开发者 https://www.devze.com 2023-02-08 17:04 出处:网络
I need to use java-legacy code with the following method: public void doit(Map <String, Object> vals) {...}

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.HashM开发者_开发知识库ap[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?


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'


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)


  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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号