【问题标题】:Type parameter issue in Scala with generic functionScala中具有通用函数的类型参数问题
【发布时间】:2016-03-30 21:47:55
【问题描述】:

我正在尝试使用类型参数 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类型,但是它不起作用。

如何解决这个问题?

【问题讨论】:

  • 通过这样的声明,您可以为Integral[T] 类型的方法引入一个隐式参数。 Scala 对&lt;T extends SomeType&gt; 的模拟是[T &lt;: SomeType]

标签: scala generics polymorphism type-parameter


【解决方案1】:

类型签名 def func[T: Integral](arg: T) = {} 实际上是以下的句法简写: def func[T](arg: T)(implicit ev: Integral[T]) = {}(“ev”通常被选为这个“证据”参数的名称。)

Integral trait 概述了您随后对T 类型的元素使用的操作。例子:加法是ev.plus(t1, t2)

如果您是import Integral.Implicits._,那么您可以使用更自然的中缀表示法:t1 + t2

不幸的是,Integral trait 不包括像 &amp;&gt;&gt; 这样的按位运算。

如果您可以修改您的算法以仅使用那些可用的操作,您将获得您所追求的功能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-19
    • 1970-01-01
    • 1970-01-01
    • 2015-12-28
    • 2016-01-25
    • 1970-01-01
    • 2018-10-24
    • 1970-01-01
    相关资源
    最近更新 更多