Alan Coromano
Alan Coromano

Reputation: 26008

Access to nested map's values

I have a Map

val m = Map(1->13, 2->Map(3->444, 4-> List("aaa", "bbb")))

I want to get its nested values:

// these all lead to an error
m.get(2)(3)
m.get(2).get(3)
m.get(2).get.get(3)

How do I do that?

Upvotes: 3

Views: 3687

Answers (2)

Jatin
Jatin

Reputation: 31724

You have a map which has inconsistent types of key-value pairs. Hence there cannot be one generalized answer.

Firstly m.get(2) returns an Option[Any]. Doing m.get(2)(3) is basically trying to do:

val option = m.get(2) //option is of type Option[Any]
option(3) //error

Hence you need to do:

m.get(2) match {
case Some(i) => i match {
     case j:Map[Any,Any] => j(3)
     }
 }

Something of this sort.

Upvotes: 1

senia
senia

Reputation: 38045

You have lost type information.

You could actually do what you want, but it's not typesafe.

m.get(2).flatMap{ case m2: Map[Int, _] => m2.get(3) }

Since you have lost type information you have to cast explicitly, so if you want to get list's element you should do something like this:

m.get(2).flatMap{ case m2: Map[Int, _] => m2.get(4) }.map{ case l: List[_] => l(1) }

You should try to save type information. At least you could use Either.

Upvotes: 5

Related Questions