I have a nested map m which is like:
m = Map("email" -> "a@b.com", "background" -> Map("language" -> "english"))
I have an array arr = Array("background","language")
How do I foldLeft/reduce the array and find the string “english” from the map. I tried this:
arr.foldLeft(m) { (acc,x) => acc.get(x) }
But I get this error:
<console>:10: error: type mismatch;
found : Option[java.lang.Object]
required: scala.collection.immutable.Map[java.lang.String,java.lang.Object]
arr.foldLeft(m) { (acc,x) => acc.get(x) }
You should pay attention to types. Here, you start with
m : Map[String, Any]as your acc. You combine with a stringxand callsget, which returns anOption[Object]. To continue, you must check that there is a value, check whether this value is aMap, cast (unchecked because of type erasure, hence dangerous).I believe the fault is in the that the type of your structure, Map[String, Any] represents what you have rather poorly.
Suppose you do instead
You may add some helpers to make declaring a Tree easy
Then declaring the tree is just as easy as your first version, but the type is much more precise
You can then add methods, for instance in
trait TreeOr if you would rather do it with a fold