使用泛型函数在 Scala 中输入参数问题
Type parameter issue in Scala with generic function
我正在尝试使用类型参数 T 提出一个通用函数 (toBitSet)。
def toBitSet[T:Integral](x:T, valueBitwidth:Int, filterBitwidth:Int, bigEndian:Boolean = true, shift:Int = 0) = {
BitSet((for (i <- 0 to (valueBitwidth - 1) if (((x & 0xFF) >> i) & 1) == 1) yield (i + shift)): _*)
}
byteToBitSet 和 shortToBitSet 函数是通用函数的特例。
def byteToBitSet(x:Byte, filterBitwidth:Int, bigEndian:Boolean = true, shift:Int = 0) = {
toBitSet[Byte](x = x, valueBitwidth = 8, filterBitwidth = filterBitwidth, bigEndian = bigEndian, shift = shift)
}
def shortToBitSet(x:Short, filterBitwidth:Int, bigEndian:Boolean = true, shift:Int = 0) = {
toBitSet[Short](x = x, valueBitwidth = 16, filterBitwidth = filterBitwidth, bigEndian = bigEndian, shift = shift)
}
但是,Scala 无法理解类型 T 上的运算符(>>、&、==、+)来显示错误消息。我指定 T
是 Integral 类型,但它不起作用。
如何解决这个问题?
类型签名
def func[T: Integral](arg: T) = {}
实际上是语法 shorthand 用于:
def func[T](arg: T)(implicit ev: Integral[T]) = {}
("ev" 通常被选为此 "evidence" 参数的名称。)
Integral trait 概述了您随后对 T
类型的元素使用的操作。示例:加法为 ev.plus(t1, t2)
如果你 import Integral.Implicits._
那么你可以使用更自然的中缀表示法:t1 + t2
不幸的是,Integral 特性不包括像 &
和 >>
这样的位运算。
如果您可以修改您的算法以仅使用那些可用的操作,您将获得您想要的功能。
我正在尝试使用类型参数 T 提出一个通用函数 (toBitSet)。
def toBitSet[T:Integral](x:T, valueBitwidth:Int, filterBitwidth:Int, bigEndian:Boolean = true, shift:Int = 0) = {
BitSet((for (i <- 0 to (valueBitwidth - 1) if (((x & 0xFF) >> i) & 1) == 1) yield (i + shift)): _*)
}
byteToBitSet 和 shortToBitSet 函数是通用函数的特例。
def byteToBitSet(x:Byte, filterBitwidth:Int, bigEndian:Boolean = true, shift:Int = 0) = {
toBitSet[Byte](x = x, valueBitwidth = 8, filterBitwidth = filterBitwidth, bigEndian = bigEndian, shift = shift)
}
def shortToBitSet(x:Short, filterBitwidth:Int, bigEndian:Boolean = true, shift:Int = 0) = {
toBitSet[Short](x = x, valueBitwidth = 16, filterBitwidth = filterBitwidth, bigEndian = bigEndian, shift = shift)
}
但是,Scala 无法理解类型 T 上的运算符(>>、&、==、+)来显示错误消息。我指定 T
是 Integral 类型,但它不起作用。
如何解决这个问题?
类型签名
def func[T: Integral](arg: T) = {}
实际上是语法 shorthand 用于:
def func[T](arg: T)(implicit ev: Integral[T]) = {}
("ev" 通常被选为此 "evidence" 参数的名称。)
Integral trait 概述了您随后对 T
类型的元素使用的操作。示例:加法为 ev.plus(t1, t2)
如果你 import Integral.Implicits._
那么你可以使用更自然的中缀表示法:t1 + t2
不幸的是,Integral 特性不包括像 &
和 >>
这样的位运算。
如果您可以修改您的算法以仅使用那些可用的操作,您将获得您想要的功能。