scala - 使用数值时的类型转换
问题描述
我试图找到一种安全的方法将具体类型 Int、Long、Double 转换回类型 T 以用于下一个代码。
所以问题是是否有替代方法可以转换为类型 T 而不是使用 isInstanceOf ?
def transform[T](x: T)(implicit e: Numeric[T]): T = {
x match {
case xInt: Int =>
// some manipulation with x
val y = xInt + 1
e.fromInt(y)
case xLong: Long =>
val y = xLong + 2
y.asInstanceOf[T]
// is there a way to convert from Long or any other numeric type
// like above for Int -> fromInt?
case xDouble =>
// same pattern
case _ => throw new Error("Type not supported")
}
}
解决方案
诸如此类的类型类的关键思想Numeric
是充当一种编译时模式匹配,它取代了运行时模式匹配。通常不需要将两者混合,所以只需调用类型类实例上的方法,编译器就会知道返回类型是T
,例如
def transform[T](a: T, b: T)(implicit num: Numeric[T]): T = {
num.plus(a, b)
}
transform(41.0, 1.0) // : Double = 42.0
transform(41, 1) // : Int = 42
transform("41", "1") // compile-time error
或获取语法糖
import Numeric.Implicits._
def transform[T](a: T, b: T)(implicit num: Numeric[T]): T = {
a + b
}
推荐阅读
- android - Firebase 项目已删除,但在 Android Studio 中仍显示已连接
- django - 动态查询 Django 构建
- regex - 增量正则表达式匹配
- java - 另一个java非法状态异常
- python - 如何使用 selenium/python 将所有 xml/dom 作为文本在父 Web 元素下获取?
- r - R 按名称选择列:dataframe$x 返回 NULL
- json - 如何将表数据转换为 d3js Sankey 的节点和链接
- javascript - 如何在仅打印 div 时在 javascript 中强制打印机设置(纸张大小)?
- azure - 通过管道安装 Azure Functions 扩展
- google-cloud-platform - 此消息的原因是什么?“无法选择我们在 Google Compute Engine 上运行。”