0

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?

3
  • 1
    are you sure val row1 = new HashMap[String,String](Map("code" -> "B1", "name" -> "Store1")) works? Commented Mar 18, 2018 at 12:00
  • yes, it's a JasperReports program that works fine Commented Mar 18, 2018 at 12:00
  • Passing a Scala immutable Map to java.util.HashMap does not seem correct. And post might be a duplicate: stackoverflow.com/questions/3843445/… Commented Mar 18, 2018 at 12:03

1 Answer 1

2

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

3 Comments

how do you define mySequence ? What needs to be changed in the code posted in the question?
@ps0604 Doesn't matter. The point is that you can just call toMap on your sequence and you'll get a map.
Thanks, this works val mapx = values.map { row => new HashMap[String,String](row.map( col => "someName" -> col).toMap) }

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.