对象上的 Scala F-bounded 多态性

Scala F-bounded polymorphism on object

我无法在 Scala 中编写以下 F 有界多态性。为什么?

trait X[T <: X[T]]
object Y extends X[Y]

我如何表达它并使其编译?

将其更改为:

  trait Y extends X[Y]

object 不是 Scala 中的类型,而是所谓的伴随对象。 通过定义 object Y,您不能表示它应该扩展 trait T[Y],因为第二个 Y 指的是尚未定义的类型 Y。 但是,您可以执行以下操作:

trait Y extends X[Y]          //If you try this on the REPL, do :paste before
object Y extends X[Y]

在这种情况下,对象 Y 扩展 X[Y] 其中第二个 Y 是您刚刚定义的特征,请务必牢记这一点。

看来你真的应该会写,

trait X[T <: X[T]]
object Y extends X[Y.type]

但是,如果您尝试编译器会给您一个无用的(我认为是虚假的)错误,

scala> object Y extends X[Y.type]
<console>:16: error: illegal cyclic reference involving object Y
       object Y extends X[Y.type]

我说 "spurious" 因为我们可以用一些额外的基础结构构造一个等效的对象,

trait X[T <: X[T]]

trait Fix { type Ytype >: Y.type <: Y.type; object Y extends X[Ytype] }
object Fix extends Fix { type Ytype = Y.type }
import Fix.Y

如果您想在实际代码中对此进行试验,使用包对象代替 object Fix 会使这个惯用语更有用。