Search code examples
scaladata-structureshashmaptuples

How do I create an empty map in Scala using a Tuple as a key?


In Scala, a Map can be created using a Tuple as a key with the following:

val userMap = mutable.HashMap(
    (1, 25) -> "shankar",
    (2, 35) -> "ramesh")

How do I do this, but initialize it as an empty Map?

Theoretical syntax: But it does not seem work in the way described: it seems to create a HashMap with a key of Int and value of Int (because it is entered as pair) and then disregards String:

val userMap = mutable.HashMap[(Int, Int), String]()

Solution

  • The posted code works fine. I have to guess that "it does not seem to work" because you're not using correct syntax to test the resulting HashMap.

    import scala.collection.mutable
    
    val userMap = mutable.HashMap[(Int, Int), String]()
    
    userMap.update((1,1) , "blah")
    userMap((1,1))  //res1: String = blah
    

    You should post the code that actually doesn't work, along with the error, instead of trying to describe what "does not seem to work."