Search code examples
scalaaopmixins

AOP-style Mixin Composition in Scala


I'm trying to use mixins to get AOP/interceptor-like style of programming.

Here's my code:

trait X {
  def run
}

trait Y extends X {
  abstract override def run = {
    println("hi")
    super.run
  }
}

object Z extends X with Y {
  def run = println("bye")
}

I get the following error when trying to compile:

method run needs `override' modifier

What am I doing wrong here? I tried to add the 'override' modifier, but than it gives me:

method run needs `abstract override' modifiers


Solution

  • One way you can do it, is to define base functionality in a class A extending the base X, and to provide an object (or a class) that mixes A and Y (and all the other traits you may define):

    trait X {
      def run
    }
    
    trait Y extends X {
      abstract override def run = {
        println("hi")
        super.run
      }
    }
    
    class A extends X {
      def run = println("bye")
    }
    
    object Z extends A with Y
    

    Z.run will print

    hi
    bye