1

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 Answers 3

8

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'
Sign up to request clarification or add additional context in comments.

Comments

2

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)

Comments

1
  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)

Comments

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.