How to implement that generic function with TypeTag in Scala?

南笙酒味 提交于 2019-12-24 10:38:52

问题


Suppose I need to write a function convert[T]: String => Option[T], which works as follows:

 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] = ???

Should I use TypeTag to implement it ?


回答1:


No, you should use the typeclass pattern. That way the types are resolved at compile time rather than runtime, which is much safer.

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)

The correct ConvertorFor is resolved implicitly at compile time. If you try to call convert with a type for which there is no implicit ConverterFor available, it will fail to compile.



来源:https://stackoverflow.com/questions/29342913/how-to-implement-that-generic-function-with-typetag-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!