1

I have an array of maps. In these maps, there is one key whose value is a map itself. It looks like this.

ArrayOfMaps = [{K1: V1, K2: V2, K3: { k1: v1, k2: v2} }, {K1': V1', K2': V2', K3': {k1': v1', k2': v2'}} ... ]

I want to have an if condition for k1 (and k1' and k1'' and so on), and if the map passes that condition I want to store that map in another list. I know it's pretty easy, I am not from a scala background. What would be the most efficient way to do this

1 Answer 1

2

First, let me ask you a question: what is the type of your ArrayOfMaps variable? If you were to annotate the type explicitly, what would you declare it as?

Even though Scala has type inference, it is still a statically typed language. Your variable will have a (static) type, and this will determine what methods are available on it. And this is a problem here, because the value type of some keys in the map is a V, and the value type of other keys in the map is a Map[K, V]. (In fact, it's a Map[K, <whatever the overall type is>] due to the recursive nesting.)

So I would suggest designing what's effectively a union type to represent these two possibilities, for example:

trait MapRhs[K, V]
case class JustValue[K, V](v: V) extends MapRhs[K, V]
case class NestedMap[K, V](m: Map[K, MapRhs[K, V]]) extends MapRhs[K, V]

Now you can state that your ArrayOfMaps is a Map[K, MapRhs[K, V]], and the value type has a more specific type than just Object.

When it comes to processing the values however, you almost certainly can't write a single piece of code that runs just as well on a V as it does on a nested map. So the most pragmatic way to handle this would be to pattern match:

ArrayOfMaps mapValues {
    case JustValue(x) => // do something with the V1
    case NestedMap(m) => // handle the map
}

If your condition is static (or can be parameterised), then instead of pattern matching you could declare it on your trait. E.g. something like (without knowing any specifics):

trait MapRhs[K, V] {
   def meetsYourCondition: Boolean
}
case class JustValue[K, V](v: V) extends MapRhs[K, V] {
   def meetsYourCondition = // some implementation for a V1
}
case class NestedMap[K, V](m: Map[K, MapRhs[V]]) extends MapRhs[K, V] {
   def meetsYourCondition = // some implementation for a nested map
}

// Now the transformation can be
ArrayOfMaps mapValues (_.meetsYourCondition)

And if you can reduce each element of the map into a boolean true-or-false, then you can turn this into an overall answer by using forall or exists instead of map (equivalent to joining with && and || respectrively).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.