Method invocation over a superclass in a self-tuning attribute in scala

I am trying to create a feature that, when mixed, will replace the standard definition of the method with the one that calls the original method, and then processes the result.

Here is what I am trying to do:

class Foo { def bar() : String = "Foos bar" } trait OtherStuff { self : Foo => def bar() : String = self.bar() + " with OtherStuff" } class Quux extends Foo with OtherStuff 

If this worked the way I wanted it, then (new Quux).bar will now return Foos bar with OtherStuff . Unfortunately, this is not the case: I get:

 <console>:6: error: error overriding method bar in class Foo of type ()String; method bar in trait OtherStuff of type ()String needs `override' modifier class Quux extends Foo with OtherStuff 

But if I use override when defining OtherStuff , I get:

 <console>:7: error: method bar overrides nothing override def bar() : String = self.bar() + " with OtherStuff" 

Is it possible to override a method in self-type using an attribute? If not, OtherStuff will be changed as a sign of extends Foo , and not one that has its own type Foo , something bad for all the code that exists, saying things like

 class WhatEver extends Foo with Xyz with Pqr with OtherStuff with Abc 

I work in scala 2.7.7 because it is an sbt build rule, and we have not yet updated our sbt project to versions 0.10.x. (The plugins we depend on are not ready yet)

+21
scala
Jul 27 '11 at 18:51
source share
2 answers

For this you need an abstract override and do not use the self type for it.

 trait OtherStuff extends Foo { abstract override def bar() = super.bar() + " with OtherStuff" } 

Then class Quux extends Foo with OtherStuff does what you want.

This article may be of interest.

+29
Jul 27 '11 at 19:02
source share

or you can perform an overload as shown below.

 class Foo { def bar() : String = "Foos bar"} trait OtherStuff { self : Foo => def bar( s : String) : String = self.bar() + s} class Quux extends Foo with OtherStuff (new Quux).bar(" with other stuff") 

A thing with a type annotation defined in OtherStuff is part of Foo when Limit is mixed with Foo, not a subtype.

0
Mar 04 '14 at 11:04
source share



All Articles