如何在Scala中使用TypeTag实现该泛型函数?

时间:2015-03-30 09:41:55

标签: scala types reification

假设我需要编写一个函数convert[T]: String => Option[T],其工作原理如下:

 import scala.util.Try

 def toInt(s: String): Option[Int] = Try(s.toInt).toOption
 def toDouble(s: String): Option[Double] = Try(s.toDouble).toOption
 def toBoolean(s: String): Option[Boolean] = Try(s.toBoolean).toOption

 // if T is either Int, Double, or Boolean return 
 // toInt(s), toDouble(s), toBoolean(s) respectively

 def convert[T](s: String): Option[T] = ???

我应该使用TypeTag来实现它吗?

1 个答案:

答案 0 :(得分:4)

不,你应该使用类型类模式。这样,类型在编译时而不是运行时解析,这样更安全。

trait ConverterFor[T] {
  def convert(s: String): Option[T]
}
object ConverterFor {
  implicit def forInt = new ConverterFor[Int] {
    def convert(s: String) = Try(s.toInt).toOption }
  implicit def forDouble = ...
}

def convert[T](s: String)(implicit converter: ConverterFor[T]): Option[T] =
  converter.convert(s)

在编译时隐式解析正确的ConvertorFor。如果您尝试使用没有隐式convert的类型调用ConverterFor,则无法编译。