将F有界类型表示为抽象类型成员

时间:2015-02-02 18:00:21

标签: scala parametric-polymorphism abstract-type f-bounded-polymorphism

我想将F有界多态转换为抽象类型成员。

trait FBoundedMovable[Self <: FBoundedMovable[Self]] {
  def moveTo(pos: Vect2): Self
}

trait Movable { self =>
  type Self <: (Movable { type Self = self.Self })

  def moveTo(pos: Vect2): Self
}

到目前为止一切顺利。

让我们定义一个实例:

case class Ship(pos: Vect2) extends Movable {
  type Self = Ship

  def moveTo(pos: Vect2) = copy(pos = pos)
}

尝试使用它:

// [error]  found   : a.Self
// [error]  required: A
  def move[A <: Movable](a: A, to: Vect2): A = a.moveTo(to)

F有界版本工作正常。

def moveF[A <: FBoundedMovable[A]](a: A, to: Vect2): A = a.moveTo(to)

我知道可以在方法定义网站上添加类型边界:

def move2[A <: Movable { type Self = A }](a: A, to: Vect2): A = a.moveTo(to)

但是可以在Movable trait声明中指定关系吗?如果没有 - 为什么?

编辑1

我意识到我遇到了什么问题。

让我们说我们想宣布某事是我们世界的一个单位。

trait WorldUnit extends Movable with Damageable

所有装置都是可移动且可损坏的。

我们的战斗计算东西只关心东西是Movable with Damagable。它不关心它是单位还是建筑物。

但是我们可以使用这样的代码:

def doCombat(obj: Movable with Damagable) = obj.moveTo(...).takeDamage(...)
def doStuffWithUnit(obj: WorldUnit): WorldUnit = doCombat(obj) // and the type is lost here.

我是否注定了F有界类型?

编辑2:

Attempting to model F-bounded polymorphism as a type member in Scala没有回答这个问题 - 我之前尝试过这个问题并且它不会影响返回类型,它仍然是一个自我。

编辑3:

我找到了http://blog.jessitron.com/2014/02/when-oo-and-fp-meet-mytype-problem.html,但问题仍未解决。

基本上,每当你有一个集合并想要选择一个:

(collection: Seq[Movable]).collectFirst { m: Movable if m.someCondition => m } - 你无法指定类型绑定,因此编译器无法证明A#Self =:= A?

1 个答案:

答案 0 :(得分:3)

scala中的类型 - 投影与路径有关。快速示例

scala> trait A{
     | type T
     | }
defined trait A

scala> val a = new A{type T = String}
a: A{type T = String} = $anon$1@31198ceb

scala> val b = new A{type T = String}
b: A{type T = String} = $anon$1@236ab296

scala> def f(implicit evidence: A =:= b.T) = null
f: (implicit evidence: =:=[A,b.T])Null

scala> f("asdf":a.T)
<console>:12: error: type mismatch;
 found   : a.T
    (which expands to)  String
 required: =:=[A,b.T]
    (which expands to)  =:=[A,String]
              f("asdf":a.T)
                      ^

在您的情况下,由于返回类型,它会抛出错误。它正确地期望a.type,但您返回A。他们不一样。

他们不应该是相同的原因是: a.type会返回<: Movable类型。对于想象力,某些数字x小于100.方法move返回A,而对于想象,它是另一个数字y小于100.它不一定是x应该与y相同。