首页 > 解决方案 > 使用数值时的类型转换

问题描述

我试图找到一种安全的方法将具体类型 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")
        }
      }

标签: scala

解决方案


诸如此类的类型类的关键思想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
}

推荐阅读