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

How to implement that generic function with TypeTag in Scala?

假设我需要写一个函数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 来实现吗?

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

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 是在编译时隐式解析的。如果您尝试使用没有可用隐式 ConverterFor 的类型调用 convert,它将无法编译。