0
votes

The following Scala code that uses java.util.HashMap (I need to use Java because it's for a Java interface) works fine:

val row1 = new HashMap[String,String](Map("code" -> "B1", "name" -> "Store1"))
val row2 = new HashMap[String,String](Map("code" -> "B2", "name" -> "Store 2"))
val map1 = Array[Object](row1,row2) 

Now, I'm trying to dynamically create map1 :

val values: Seq[Seq[String]] = ....
val mapx = values.map {
      row => new HashMap[String,String](Map(row.map( col => "someName" -> col)))  <-- error
     }
val map1 = Array[Object](mapx) 

But I get the following compilation error:

type mismatch; found : Seq[(String, String)] required: (?, ?)

How to fix this?

1
are you sure val row1 = new HashMap[String,String](Map("code" -> "B1", "name" -> "Store1")) works?Ramesh Maharjan
yes, it's a JasperReports program that works fineps0604
Passing a Scala immutable Map to java.util.HashMap does not seem correct. And post might be a duplicate: stackoverflow.com/questions/3843445/…user3097405

1 Answers

2
votes

We can simplify your code a bit more:

val mapx = Map(Seq("someKey" -> "someValue"))

This still produces the same error message, so the error wasn't actually related to your use of Java HashMaps, but trying to use a Seq as an argument to Scala's Map.

The problem is that Map is variadic and expects key-value-pairs as its arguments, not some data structure containing them. In Java a variadic method can also be called with an array instead, without any type of conversion. This isn't true in Scala. In Scala you need to use : _* to explicitly convert a sequence to a list of arguments when calling a variadic method. So this works:

val mapx = Map(mySequence : _*)

Alternatively, you can just use .to_map to create a Map from a sequence of tuples:

val mapx = mySequence.toMap