Assuming we have a model of something, represented as a case class
, as so
case class User(firstName:String,lastName:String,age:Int,planet:Option[Planet])
sealed abstract class Planet
case object Earth extends Planet
case object Mars extends Planet
case object Venus extends Planet
Essentially, either by use of reflection, or Macros, to be able to get the field names of the User case class, as well as the types represented by the fields. This also includes Option
, i.e. in the example provided, need to be able to differentiate between an Option[Planet]
and just a Planet
In scala'ish pseudocode, something like this
val someMap = createTypedMap[User] // Assume createTypedMap is some function which returns map of Strings to Types
someMap.foreach{case(fieldName,someType) {
val statement = someType match {
case String => s"$fieldName happened to be a string"
case Int => s"$fieldName happened to be an integer"
case Planet => s"$fieldName happened to be a planet"
case Option[Planet] => s"$fieldName happened to be an optional planet"
case _ => s"unknown type for $fieldName"
}
println(statement)
}
I am currently aware that you can't do stuff like case Option[Planet]
, since it gets erased by Scala's erasure, however even when using TypeTags
, I am unable to wrote code that does what I am trying to do, and possibly deal with other types (like Either[SomeError,String]
).
Currently we are using the latest version of Scala (2.11.2) so any solution that uses TypeTags
or ClassTags
or macros would be more than enough.