Tiago Babo
Tiago Babo

Reputation: 1344

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

Upvotes: 3

Views: 360

Answers (2)

user5102379
user5102379

Reputation: 1512

You should create base abstract class:

abstract class A {
  def run
}

Then extend it with X or Y:

trait X extends A /* OR trait Y extends A */ {
  def run
}

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

Then move Z.run to super class:

class S extends A {
  def run = println("bye")
}

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

Z.run
// hi
// bye 

Upvotes: 1

Kolmar
Kolmar

Reputation: 14224

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

Upvotes: 4

Related Questions