Question

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?
Was it helpful?

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 {


 ^
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top