简体   繁体   English

Scala F-bound对象的多态性

[英]Scala F-bounded polymorphism on object

I cannot write the following F-bounded polymorphism in Scala. 我不能在Scala中编写以下F-bounded多态。 Why? 为什么?

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

How can I express this and make it compile? 我怎样才能表达并编译?

It really seems like you ought to be able to write, 看起来你真的应该能够写作,

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

however, if you try that the compiler will give you an unhelpful (and I think spurious) error, 但是,如果你尝试编译器会给你一个无用的(我认为是虚假的)错误,

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

I say "spurious" because we can construct an equivalent object with a little bit of additional infrastructure, 我说“虚假”,因为我们可以构建一个具有一点额外基础设施的等效对象,

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

If you wanted to experiment with this in real code, using a package object in place of object Fix would make this idiom a little more usable. 如果你想在实际代码中试验这个,使用一个包对象来代替object Fix会使这个成语更加有用。

Change it to : 将其更改为:

  trait Y extends X[Y]

object is not a type in Scala, but the so called companion object. object不是Scala中的类型,而是所谓的伴随对象。 By defining object Y , you can't express that it should extend trait T[Y] , since that second Y refers to a type Y that hasn't been defined. 通过定义object Y ,您无法表达它应该扩展trait T[Y] ,因为第二个Y指的是尚未定义的类型Y You can however do the following: 但是,您可以执行以下操作:

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

In this case the object Y extends X[Y] where the second Y is the trait you just define, make sure you keep this in mind. 在这种情况下,对象Y扩展X[Y] ,其中第二个Y是您刚定义的特征,请确保记住这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM