sujit
sujit

Reputation: 2328

flatMap within recursive function to return a List of case class objects

I have a heavily nested Map[String, Any] (got from a parsed JSON). My intent is to convert this (flatten this) to a List of case class objects by recursing through the Map and populating the object from the map key+value. I am using flatMap within a recursive function but I am getting compilation issue:

<console>:30: error: type mismatch;  found   : scala.collection.immutable.Iterable[Derived]  required: List[Derived]
         map.flatMap {
                     ^

My code looks as follows. Please point what I am doing wrong and how to resolve?

case class Derived(a: String, b: String, c: String)
val Sep = "/"
def getDerivedList(map: Map[String, Any], prefix: String = Sep) : List[Derived] = {
  map.flatMap {
    //Handle Map as value by recursing
    case (k, v:Map[String, Any]) => getDerivedList(v, s"${prefix}${k}${Sep}")
    //Handle primitive type
    case (k, v) if (v != null && v != None) => {
      val value = if(v.isInstanceOf[Boolean]) String.valueOf(v).toUpperCase else String.valueOf(v)
      val a = "" //Custom logic from k or v
      val b = "" //Another custom logic from k or v
      val c = "" //You get it
      List(Derived(a,b,c))
    }
    case _ => List() //Catch all, will not come here as per my data
  }
}

val map: Map[String, Any] = Map("k1" -> "v1", "mk1" -> Map("mk1k2" -> "mk1v2", "mk1k3" -> Map("mk2k4" -> true)))
getDerivedList(map)

Upvotes: 1

Views: 315

Answers (1)

slouc
slouc

Reputation: 9698

Turning a Map into a List is easily done via Map's method .toList, which converts the map into a list of (key, value) tuples. Once you have a List, you can flatmap it with a function that returns a List.

However, if you flatmap a Map with such a function (that is, a function which returns a List), compiler will infer the nearest common supertype of List and Map, which is an Iterable. This is what's happening in your case.

So, simply changing to

map.toList.flatMap {

should do the trick.

Upvotes: 2

Related Questions