I'd like to build a function to read the settings from a properties file, key/value pairs, and then cast it to expected types. If the given field name does't exist, we get the default value of the specific T. Is that doable?
I put some pseudo code here and would like to know how to write the real code with the help of scala reflection.
def getField[T](fieldName: String): T =
{
val value = getField(fieldName)
if (value == null) {
T match {
case Int => 0
case Boolean => false
...
case _ => null
}
}
else value.asInstanceOf[T]
}
Alternatively, throw an exception if the field is not locate, which is not a bad idea to me... def getField[T](fieldName: String): T = { val value = getField(fieldName)
if (value == null) {
throw new Exception("error msg")
}
}
else value.asInstanceOf[T]
}
I know how to do it if it returns Option[T] (as discussed here Writing a generic cast function Scala ).