Scala 示例 - 带有上下文边界错误的特征类型参数? [英] Scala by Example - trait type parameter with context bounds mistake?

查看:49
本文介绍了Scala 示例 - 带有上下文边界错误的特征类型参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读 Scala by Example 书,当 Martin 在第 54 页解释类型边界时有这个例子:

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
}

trait Set[A <% Ordered[A]] ...

进一步在第 55 页.他还说 <:/<% 是 trait Set 所需的唯一更改,以证明类型边界的可能性.

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.

然而,当我用自己的代码重复这个例子时,IDE 会抱怨 trait 可能没有视图边界,只有类型边界.将 trait 关键字更改为抽象类或将视图绑定更改为类型绑定会有所帮助.这是书上的错误吗?

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?

推荐答案

让我们使用名为 REPL 的强大工具来了解正在发生的事情:

Let's use our powerful tool called the REPL to understand what is going on:

scala>  trait Example[A<:Ordered[A]] { def contains(x:A):Boolean }
defined trait Example

scala>  class Example2[A<%Ordered[A]]( val a:A) { def isLower(otherA:A):Boolean = a< otherA }
defined class Example2

scala>  :javap Example
Compiled from "<console>"
public interface Example{
    public abstract boolean contains(scala.math.Ordered);
}


scala>  :javap Example2
Compiled from "<console>"
public class Example2 extends java.lang.Object implements scala.ScalaObject{
    public java.lang.Object a();
    public boolean isLower(java.lang.Object);
    public Example2(java.lang.Object, scala.Function1);
}

如您所见,视图边界成为 Example2 构造函数的第二个参数.由于特征没有构造函数,因此显然不可能提供视图边界.

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.

为什么这在以前的版本中是可能的对我来说是个谜(也许在 trait 中创建了一个额外的 Function1 val 并由编译器填充?)

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?)

关于你关于Scala进化的问题,它是成熟和强大的.您可以期待主要版本(2.8、2.9、2.10)之间的变化,但我不会认为 Scala 对此不够成熟.但是,总有改进的空间

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

这篇关于Scala 示例 - 带有上下文边界错误的特征类型参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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