I have a method that should dynamically cast a field member into a certain type depending on a configuration flag format
.
This flag format
, accepts one of the following type values:
object Types {
val Str = "string"
val IntNum1 = "int"
val IntNum2 = "integer"
val DoubleNum = "double"
val LongNum = "long"
}
One option would be to use reflection. Another option would be to use pattern matching (the method I'm trying to do this with)
Here's the method for String
types:
private def getValClassIfStr(format: String): Class[String] = {
format.toLowerCase match {
case Types.Str => classOf[String]
case _ => null
}
}
And Here's the method for Numerical types, extending from AnyVal
, that fails to compile:
private def getValueClass[T <: AnyVal](format: String): Try[Class[T]] = {
format.toLowerCase match {
case Types.IntNum1 || Types.IntNum2 => Success(classOf[Int])
case Types.DoubleNum => Success(classOf[Double])
case Types.LongNum => Success(classOf[Long])
case _ => Failure(new Exception)
}
}
The second method doesn't compile because of a:
Type mismatch: required Try[Class[T]] found Try[Class[Int]]
Which I don't understand, given T <: AnyVal
.
Any idea? and if that's a bad approach, what would a "clean" alternative be?