Pablo Fernandez
Pablo Fernandez

Reputation: 105258

Scala trait composition issue

I have a class which source I cannot modify:

class Foo {

  def bar() = println("bar")

}

And a trait I'd like to mix into it at runtime

trait Zee { this: Foo =>

  abstract override def bar() = {
    println("before bar")
    super.bar()
  }
}

This is throwing that bar is not a member of Object with ScalaObject

What am I doing wrong? Is it possible to achieve this without modifying Foo source?

The ultimate client code needs to look like this:

val foo = new Foo with Zee
foo.bar() // should print 'before bar' and then 'bar'

Upvotes: 1

Views: 239

Answers (3)

Kyle
Kyle

Reputation: 22278

your trait needs to extend foo

trait Zee extends Foo {
  abstract override def bar() = {
    println("before bar")
    super.bar()
  }
}

Upvotes: 2

Juliano Alves
Juliano Alves

Reputation: 2016

You can just extends the class Foo in your trait:

trait Zee extends Foo

And your code will work.

Upvotes: 3

om-nom-nom
om-nom-nom

Reputation: 62855

Your Zee trait has no super traits (except implicit inheritance from ScalaObject) thus super does not contain definition for bar and there is nothing to override or call (super.bar).

why don't you write this without self-reference?

class Foo {

  def bar() = println("bar")

}


trait Zee extends Foo {

  abstract override def bar() = {
    println("before bar")
    super.bar()
  }
}

Upvotes: 5

Related Questions