Search code examples
scalacompiler-constructionmixinstraitsabstract-methods

Can scala compiler enforce to implement abstract trait methods when mixin in?


I have a trait with abstract methods and concrete implemented methods, so something like this:

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

Now I mixin the trait:

class MyClass extends BaseClass with MyTrait {

}

The BaseClass does not implement the abstract method. I expected the scala compiler to enforce that the abstract method must be implemented (just like a Java interface) when I mix in the trait. But there is no compiler error.

My particular case is more complicated. I was not able to test what happens at runtime, yet.

  1. Why doesn't the scala compiler enforce the implementation of the abstract method?
  2. Can I make the scala compiler enforce the implementation of the abstract method?
  3. Must I add abstract or override somewhere?
  4. What happens at runtime when I try to create and use instances of MyClass?

Solution

  • You should definitely get a compiler error...

    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 {
    
    
     ^