gpt4 book ai didi

scala - scala 编译器可以在混合时强制实现抽象特征方法吗?

转载 作者:行者123 更新时间:2023-12-01 10:30:20 25 4
gpt4 key购买 nike

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

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

现在我混合了特征:

class MyClass extends BaseClass with MyTrait {

}

BaseClass 没有实现抽象方法。我希望 scala 编译器在我混合特性时强制执行抽象方法(就像 Java 接口(interface)一样)。但是没有编译错误。

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

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

最佳答案

你肯定会得到一个编译器错误...

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 - scala 编译器可以在混合时强制实现抽象特征方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13780441/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com