简体   繁体   中英

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. 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 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. 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.

In the second case you explicitly specify that you are overriding TestTrait behavior, and then the overriden behavior is mixed into TestClass.

I think it's perfectly fine to use the second method, and that it conveys more clearly what the intention is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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