简体   繁体   中英

How to transform case class object graph to Map

I have been reading in some thread how to map a case class to a Map in scala. Unfortunately none of the answers provided are good enough.

My example would be to have something like:

case class A(a1: String, a2: String, a3: C)

case class C(c1: String, c2: String, c3: D)

case class D(d1: String, d2: String)

Assuming that we have the following instances

val d = D(d1 ="valueForD1", d2 = "valueForD2")
val c = C(c1 ="valueForc1", c2 = "valueForC2", c3 = d)
val a = A(a1 ="valueForA1", a2 = "valueForA2", a3 = c)

I want to transform that case class graph into the following form:

Map("a1" -> "valueForA1", "a2" -> "valueForA2", 
    "a3" -> Map("c1" -> "valueForC1", "c2" -> "valueForc2", 
    "c3" -> Map("d1" -> "valueForD1", "d2" -> "valueFord2")))

This is a most direct approach, not very scalable, though...

 def toGraph(a: A): Map[String, Any] = 
   a match {
     case A(a1,a2,C(c1,c2,D(d1,d2))) => Map(
       "a1" -> a1,
       "a2" -> a2,
       "a3" -> Map(
         "c1" -> c1,
         "c2" -> c2,
         "c3" -> Map(
           "d1" -> d1,
           "d2" -> d2)
         )
       )
    case _ => Map() 
  }

I suppose that for a more "dynamic" approach you can resort to macros

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM