如何在 Scala 中使用 TypeTag 实现该通用函数? [英] How to implement that generic function with TypeTag in Scala?

查看:19
本文介绍了如何在 Scala 中使用 TypeTag 实现该通用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我需要写一个函数 convert[T]: String =>Option[T],作用如下:

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

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

Should I use TypeTag to implement it ?

推荐答案

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

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)

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

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.

这篇关于如何在 Scala 中使用 TypeTag 实现该通用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆