1

I have nested map as below:

val x: Map[String, Any] = 
  Map("a" -> "apple", "b" -> "ball", "c" -> Map("x" -> "cat", "y" -> 12))

and I want to convert it into:

Map("a" -> "apple", "b" -> "ball", "x" -> "cat", "y" -> 12)

However, if I try to invoke flatten to x then I get exception.

x.flatten
Error:(40, 14) No implicit view available from (String, Any) => scala.collection.GenTraversableOnce[B].
println(mx.flatten)
Error:(40, 14) not enough arguments for method flatten: (implicit asTraversable: ((String, Any)) => scala.collection.GenTraversableOnce[B])scala.collection.immutable.Iterable[B].
Unspecified value parameter asTraversable.
println(x.flatten)

So, how can I provide implicit view in order to flatten the above map?

3
  • Have a look here: alvinalexander.com/scala/… I think flatten is the wrong approach. Commented Apr 7, 2017 at 11:43
  • What if x is already a key on the outer map? Commented Apr 7, 2017 at 11:45
  • 1
    Why do you have that data structure in the first place? Commented Apr 7, 2017 at 13:04

1 Answer 1

5

It's a bit strange you want to loose the information about 'c'.
But anyway, the compiler is complaining because it does not know how to convert the (String,Any), your Key -> Value pair into a traversable and that is logical.
You could provide the compiler with a hint that in case the 'Any' is a Map, it should only use the values and loose the key.

For example:

x.flatten {
  case ((key, map : Map[String, Any])) => map
  case ((key, value)) => Map(key -> value)
}.toMap

This returns

Map(a -> apple, b -> ball, x -> cat, y -> 12)

Note: the 'toMap' is needed because the 'flatten' returns a List[(String,Any)].

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

1 Comment

Thank you, this is really what I needed.

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.