1

我一直在阅读一些线程如何将案例类映射到 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")))
4

1 回答 1

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

我想对于更“动态”的方法,您可以求助于

于 2013-07-15T15:10:32.460 回答