softshipper
softshipper

Reputation: 34071

How to create a map key from a variable?

I would like to create a Map from variables, for example:

scala> val a = "H"
a: String = H

scala> val b = "C"
b: String = C

scala> Map(a, b)
<console>:14: error: type mismatch;
 found   : String
 required: (?, ?)
       Map(a, b)
           ^
<console>:14: error: type mismatch;
 found   : String
 required: (?, ?)
       Map(a, b)
          ^

As you can see, the compiler complains. What am I doing wrong?

Upvotes: 0

Views: 443

Answers (2)

locorecto
locorecto

Reputation: 1203

The problem in your snippet is that there is not constructor/apply method to build a Map that takes two string arguments.

The right approach/syntax for a Map of String keys and String values would be:

val a = "H"
val b = "C"
val testMap: Map[String, String] = Map(a -> b)

In general use this syntax:

val testMap: Map[K, V] = Map(k1 -> v1, k2 -> v2, ...)

Upvotes: 1

Markus Appel
Markus Appel

Reputation: 3238

Scala's syntax for instantiating Maps looks like this:

val myMap: Map[K, V] = Map(k1 -> v1, k2 -> v2, ...)

where K is the type of the keys, and V the type of the values.

Upvotes: 2

Related Questions