【问题标题】:Can scala compiler enforce to implement abstract trait methods when mixin in?混入时,scala编译器可以强制实现抽象特征方法吗?
【发布时间】:2012-11-26 15:44:17
【问题描述】:

我有一个特点是抽象方法和具体实现的方法,所以是这样的:

trait MyTrait extends BaseClass {
    def myAbstractMethod: MyReturnType
    def myConcreteMethod = { /*implementation*/ }
}

现在我混合特征:

class MyClass extends BaseClass with MyTrait {

}

BaseClass 没有实现抽象方法。当我混合特征时,我希望 scala 编译器强制必须实现抽象方法(就像 Java 接口一样)。但是没有编译错误。

我的特殊情况更复杂。我还无法测试运行时会发生什么。

  1. 为什么 scala 编译器不强制执行抽象方法?
  2. 我可以让 scala 编译器强制执行抽象方法吗?
  3. 我必须在某处添加抽象或覆盖吗?
  4. 当我尝试创建和使用 MyClass 的实例时,运行时会发生什么?

【问题讨论】:

  • 当我在同一个文件/项目中出现其他错误(但在工作区中的其他项目中没有)时,我刚刚遇到了这个问题。我将 Eclipse 4.5 (Mars) 与 Scala 4.2.0 一起使用。我已将此报告为错误:assembla.com/spaces/scala-ide/support/tickets/…

标签: scala compiler-construction mixins traits abstract-methods


【解决方案1】:

您肯定会遇到编译器错误...

scala> :paste
// Entering paste mode (ctrl-D to finish)

trait MyTrait extends BaseClass {
    def myAbstractMethod: MyReturnType
    def myConcreteMethod = { /*implementation*/ }
}

class MyClass extends BaseClass with MyTrait {    
}


// Exiting paste mode, now interpreting.

<console>:14: error: class MyClass needs to be abstract, since method myAbstractMethod in trait MyTrait of type => MyReturnType is not defined
       class MyClass extends BaseClass with MyTrait {


 ^

【讨论】:

  • 这很奇怪。我使用 Scala IDE for Eclipse,在我们讨论的类/特征中没有这样的编译器错误。我进行了重大重构并且遇到了一些编译器错误,但只是在其他一些完全独立于我们所讨论的类中。现在我完全注释掉了那些错误的类,相关特征中出现了新的错误。似乎 eclipse scala 插件或其他东西没有像我预期的那样处理这个问题。
猜你喜欢
  • 2021-10-16
  • 2013-10-31
  • 1970-01-01
  • 2012-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多