I have two nested case classes:
case class InnerClass(param1: String, param2: String)
case class OuterClass(myInt: Int, myInner: InnerClass)
val x = OuterCla
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.