Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access to nested map's values

Tags:

scala

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?

like image 408
Alan Coromano Avatar asked Feb 13 '26 04:02

Alan Coromano


2 Answers

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.

like image 55
senia Avatar answered Feb 15 '26 18:02

senia


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.

like image 44
Jatin Avatar answered Feb 15 '26 18:02

Jatin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!