Convert Nested Case Classes to Nested Maps in Scala

前端 未结 3 1240
野趣味
野趣味 2021-01-15 03:04

I have two nested case classes:

case class InnerClass(param1: String, param2: String)
case class OuterClass(myInt: Int, myInner: InnerClass)
val x = OuterCla         


        
3条回答
  •  星月不相逢
    2021-01-15 03:15

    As Luigi Plinge notes in a comment above, this is a very bad idea—you're throwing type safety out the window and will be stuck with a lot of ugly casts and runtime errors.

    That said, it's pretty easy to do what you want with the new Scala 2.10 Reflection API:

    def anyToMap[A: scala.reflect.runtime.universe.TypeTag](a: A) = {
      import scala.reflect.runtime.universe._
    
      val mirror = runtimeMirror(a.getClass.getClassLoader)
    
      def a2m(x: Any, t: Type): Any = {
        val xm = mirror reflect x
    
        val members = t.declarations.collect {
          case acc: MethodSymbol if acc.isCaseAccessor =>
            acc.name.decoded -> a2m((xm reflectMethod acc)(), acc.typeSignature)
        }.toMap
    
        if (members.isEmpty) x else members
      }
    
      a2m(a, typeOf[A])
    }
    

    And then:

    scala> println(anyToMap(x))
    Map(myInt -> 11, myInner -> Map(param1 -> hello, param2 -> world))
    

    Do not do this, though. In fact you should do your absolute best to avoid runtime reflection altogether in Scala—it's really almost never necessary. I'm only posting this answer because if you do decide that you must use runtime reflection, you're better off using the Scala Reflection API than Java's.

提交回复
热议问题