Scala - 如何定义引用自身的结构类型? [英] Scala - how to define a structural type that refers to itself?

查看:43
本文介绍了Scala - 如何定义引用自身的结构类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个通用的 interpolate 方法,该方法适用于具有两种方法的任何类型,一个 * 和一个 +,像这样:

I'm trying to write a generic interpolate method that works on any type that has two methods, a * and a +, like this:

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 上),但我收到以下错误消息:

This doesn't work though (on Scala 2.8.0.RC7), I get the following error messages:

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

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

How do I specify the structural type correctly? (Or is there a better way to do this?)

推荐答案

您当然可以使用 typeclasses 方法(例如 Scalaz):

Surely you could solve this problem using the typeclasses approach (of e.g. 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

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

Then obviously you would need a (implicit) typeclass conversion in scope for all the types you cared about:

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

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

Then this can be run easily:

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

  println(j) //prints 6
}

这篇关于Scala - 如何定义引用自身的结构类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆