如何将案例类对象图转换为Map

时间:2013-07-15 13:25:42

标签: scala

我一直在阅读一些线程如何将案例类映射到scala中的Map。不幸的是,所提供的答案都不够好。

我的例子就是:

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)

假设我们有以下实例

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)

我想将该案例类图转换为以下形式:

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

1 个答案:

答案 0 :(得分:-1)

这是一种最直接的方法,虽然不是很容易扩展......

 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() 
  }

我想这是为了更多"动态"您可以诉诸macros