Scala 示例 - 具有上下文边界错误的特征类型参数?
阅读《Scala by Example》一书,Martin 在第 54 页以及
trait Set[A <: Ordered[A]] {
def incl(x: A): Set[A]
def contains(x: A): Boolean
}
第
trait Set[A <% Ordered[A]] ...
55 页上解释了类型界限时,有一个示例。他还说 <:/<% 是为了证明特征集所需的唯一更改类型限制的可能性。
然而,当我用自己的代码重复该示例时,IDE 抱怨特征可能没有视图边界,只有类型边界。将特征关键字更改为抽象类或将视图绑定更改为类型绑定会有所帮助。这是书上的错误吗?
Reading the Scala by Example book and there is this example when Martin explains type bounds on page 54:
trait Set[A <: Ordered[A]] {
def incl(x: A): Set[A]
def contains(x: A): Boolean
}
and
trait Set[A <% Ordered[A]] ...
further on page 55. He also says that the <:/<% is the only change required for trait Set in order to demonstrate the type bounding possibilities.
However, when I repeat the example with my own code, the IDE complains that traits may NOT have view bounds, only type bounds. Changing the trait keyword to abstract class or changing the view bound to type bound helps. Is this a mistake in the book?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
让我们使用名为 REPL 的强大工具来了解正在发生的事情:
如您所见,视图绑定成为 Example2 构造函数的第二个参数。由于特征没有构造函数,因此显然不可能提供视图绑定。
为什么这在以前的版本中是可能的,对我来说是一个谜(也许在特征内创建了一个额外的 Function1 val 并由编译器填充?)
关于您关于 Scala 演变的问题,它是成熟且强大的。您可以预期主要版本(2.8、2.9、2.10)之间的变化,但我不认为 scala 对此还不够成熟。然而,总是有改进的空间
Let's use our powerful tool called the REPL to understand what is going on:
As you can see , the view bound becomes the second argument of the Example2 constructor. Since a trait does not have a constructor, clearly it is not possible to provide a view bound.
Why this has been possible in previous releases is to me a mistery (maybe an additional Function1 val was created inside the trait and filled by the compiler?)
Concerning your question about Scala evolution, it is mature and powerful. You can expect changes between major releases (2.8, 2.9, 2.10) but I would not consider scala not mature enough for this. There is, however, always space for improvement