Jason
Jason

Reputation: 2915

Selecting trait to inherit common method from in Scala

Suppose that I create a class mixing in two traits, both of which implement a common method, as follows for instance:

abstract class Base {
    var x:Int
    def adder:Int
}

trait One extends Base {
    def adder() = {x+=2; x}
}

trait Two extends Base {
    def adder() = {x+=3; x}
}

class WhichOne(var x:Int = 10) extends Base with One with Two

println((new WhichOne()).adder())

At runtime, Scala of course complains since it has no idea which trait to prefer:

$ scala MixUpTraitImplems.scala 
MixUpTraitImplems.scala:18: error: class WhichOne inherits conflicting members:
  method adder in trait One of type ()Int  and
  method adder in trait Two of type ()Int
(Note: this can be resolved by declaring an override in class WhichOne.)
class WhichOne(val x:Int = 10) extends Base with One with Two
      ^

Of course, overriding adder() would mean that I go ahead and implement a new version of adder, but what if I don't want that? What if I want to use the implementation of adder explicitly contained in trait One or Two?

Upvotes: 3

Views: 3174

Answers (2)

marios
marios

Reputation: 8996

One way is to override the adder to just call the adder of the it's super class. In this case, it will be the rightmost trait/class that implements adder (in the example below, it will be the adder of the One trait).

class WhichOne(var x:Int = 10) extends Base with Two with One {
   override def adder() = super.adder()
}

Upvotes: 1

Alexey Romanov
Alexey Romanov

Reputation: 170735

You can specify this as a modifier to super: override def adder() = super[One].adder(). Also note that this is a compile-time error, not runtime!

Upvotes: 9

Related Questions