vendredi 4 septembre 2015

Reflect type name in String to actual type in Scala

I've the following class-object

class DefaultValue[+A](val default: A)

object DefaultValue {

  implicit object DefaultDouble extends DefaultValue[Double](-1.0)
  implicit object DefaultFloat extends DefaultValue[Float](-1f)
  implicit object DefaultInt extends DefaultValue[Int](-1)
  implicit object DefaultBoolean extends DefaultValue[Boolean](false)

  def value[A](implicit value: DefaultValue[A]): A = value.default
}

To use this I call DefaultValue.value[Int] or DefaultValue.value[Double] etc

However, I need the ability to call DefaultValue.value[Int] when I have user input as "Int" : the typename written in String, and similarly for others.

I wish to do this without pattern-matching, as it would essentially beat the purpose of inserting TypeTag in the function. Is there a better way to do this, perhaps using Scala Reflection?





Aucun commentaire:

Enregistrer un commentaire