简体   繁体   English

在Scala中为最终课程覆盖特征方法

[英]Override a trait method for final class in Scala

Consider the following: 考虑以下:

trait TestTrait {
  def doStuff()
}

final class TestClass {
// ...
}

I would like to instantiate an instance of TestClass that implements the method in the trait. 我想实例化一个实现特质中方法的TestClass实例。 The following does not compile: 以下内容无法编译:

// Illegal inheritance from final class TestClass
val t = new TestClass with TestTrait {
  def doStuff() {
    println("doing stuff")
  }
}

This makes sense, since the anonymous class created would extend the final class. 这是有道理的,因为创建的匿名类将扩展最终类。 What I'm really after is an anonymous implementation of the trait mixed in to an instance of the final class. 我真正想要的是将特性的匿名实现混入最终类的实例中。

The following works, but seems a bit roundabout. 以下工作,但似乎有点回旋处。 Is there a way to do this directly without the declared trait implementation? 没有声明的trait实现,有没有办法直接做到这一点?

trait TestTraitImpl extends TestTrait {
  def doStuff() {
    println("doing stuff")
  }
}

val t = new TestClass with TestTraitImpl

As it turns out, you can't do the latter either. 事实证明,后者也不能。

final class TestClass

trait TestTrait

val t = new TestClass with TestTrait

Apparently, any Foo with Bar is creation of a new anonymous type, and thus final classes cannot have traits as mixins. 显然,任何Foo with Bar都是创建一个新的匿名类型,因此最终类不能具有mixin的特征。 This adds a great deal of theoretical significance to making a class final, as it prevents not just the concept of inheritance, but also stackable modification. 这为最终的类添加了很大的理论意义,因为它不仅阻止了继承的概念,而且还阻止了可堆叠的修改。

Method resolution rules are different in the two cases. 在两种情况下,方法解析规则不同。 In the first case an anonymous class is constructed first by whatever happens to be the methods/attributes of the type: 在第一种情况下,首先根据类型的方法/属性构造一个匿名类:

final class TestClass with TestTrait

and then you are trying to override a method of that, which conflicts with the final qualifier of TestClass. 然后您尝试覆盖该方法,该方法与TestClass的最终限定符冲突。

In the second case you explicitly specify that you are overriding TestTrait behavior, and then the overriden behavior is mixed into TestClass. 在第二种情况下,您明确指定要覆盖TestTrait行为, 然后将覆盖的行为混合到TestClass中。

I think it's perfectly fine to use the second method, and that it conveys more clearly what the intention is. 我认为使用第二种方法非常好,并且可以更清楚地传达其意图。

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

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