recursion - Scala Case Class Recursive -
i trying recursively create key, value pair map hierarchical case class structure, no luck.
case class country(id: option[long], name: string, states: option[list[state]]) case class state(id: option[long], name: string, cities: option[list[city]]) case class city(id: option[long], name: string)
so trying extract in lists , zip key value pair, trying recursive computation obtain same in lists of objects.
val keys = country.getclass.getdeclaredfields.map(f => f.getname) val values = country.productiterator val m = (keys zip values.tolist).tomap
this gives me 3 keys values.
my problem solve recursive way in list[city] inside state , list[state] inside country.
is there way that? can't think in solution. trying iterate on map, matching there list , iterate , trying save progress in bufferlist.
has trying this?
edit
i wasn't specific desirable output.
i want child other maps, getting example @tienan ren tried this:
def tomap[t: typetag](clazz: scala.product): map[string, any] = { def recursion(key: string, list: list[t]): map[string, any] = { list.tomap } val keys = clazz.getclass.getdeclaredfields.map(_.getname) val values = (keys zip clazz.productiterator.tolist) map { case (key, value: list[t]) => recursion(key, value) case (key, value) => (key, value) } values.tomap }
where recursion should receive list , map.
not sure why use option[list[..]], empty list should capable of representing none case. here implementation after removing option lists.
case class country(id: option[long], name: string, states: list[state]) case class state(id: option[long], name: string, cities: list[city]) case class city(id: option[long], name: string)
the tomap function:
import reflect.runtime.universe._ def tomap[t: typetag](c: scala.product): map[string, any] = { val keys = c.getclass.getdeclaredfields.map(_.getname) val z = (keys zip c.productiterator.tolist) map { case (key, value: list[t]) if typeof[t] <:< typeof[scala.product] => (key, value.map(v => tomap(v.asinstanceof[scala.product]))) case (key, value) => (key, value) } z.tomap }
output:
val country = country(none, "us", list(state(none, "ca", city(none, "la") :: nil))) println(tomap(country))
this gives you:
map(id -> none, name -> us, states -> list(map(id -> none, name -> ca, cities -> list(map(id -> none, name -> la)))))
Comments
Post a Comment