I was trying to recursively create a key, value pair map from a hierarchical case class structure, but 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 I was trying to extract that in Lists and zip to get the key value pair, then trying to do some recursive computation to obtain the same in the 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 with their values.
My problem is to solve the recursive way in the List[City] inside State and List[State] inside Country.
Is there any good way to do that? I can't think in any good solution. I was trying to iterate over the map, matching where there is a List and iterate and trying to save this progress in a BufferList.
Has anyone trying to do something like this?
EDIT
I wasn't specific about the desirable output.
I want the child to be other maps, so getting the example from @Tienan Ren I tried to do something like 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 the recursion should receive the list and back a Map.
getDeclaredFieldsis not guaranteed to return fields in any order. It is implementation-dependent and can be arbitrary and may not coincide with whateverproductIteratorreturns.