8

我正在尝试编写一个通用interpolate方法,该方法适用于具有两个方法 a*和 a 的任何类型+,如下所示:

trait Container {
  type V = {
    def *(t: Double): V
    def +(v: V): V
  }

  def interpolate(t: Double, a: V, b: V): V = a * (1.0 - t) + b * t
}

这不起作用(在 Scala 2.8.0.RC7 上),我收到以下错误消息:

<console>:8: error: recursive method + needs result type
           def +(v: V): V
                        ^
<console>:7: error: recursive method * needs result type
           def *(t: Double): V
                             ^

如何正确指定结构类型?(或者有更好的方法吗?)

4

2 回答 2

9

当然,您可以使用类型类方法(例如Scalaz)解决这个问题

trait Multipliable[X] {
  def *(d : Double) : X
}

trait Addable[X] {
    def +(x : X) : X
}

trait Interpolable[X] extends Multipliable[X] with Addable[X]

def interpolate[X <% Interpolable[X]](t : Double, a : X, b : X)
    = a * (1.0 - t) + b * t

那么显然,对于您关心的所有类型,您需要在范围内进行(隐式)类型类转换:

implicit def int2interpolable(i : Int) = new Interpolable[Int] {
  def *(t : Double) = (i * t).toInt
  def +(j : Int) = i + j
}

然后这可以很容易地运行:

def main(args: Array[String]) {
  import Interpolable._
  val i = 2
  val j : Int = interpolate(i, 4, 5)

  println(j) //prints 6
}
于 2010-07-11T12:51:22.197 回答
3

AFAIK,这是不可能的。这是我自己的第一个问题

于 2010-07-08T13:04:40.087 回答