Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Traits and abstract methods override in Scala

Tags:

scala

traits

I have a base abstract class (trait). It has an abstract method foo(). It is extended and implemented by several derived classes. I want to create a trait that can be mixed into the derived classes so that it implements foo() and then calls the derived class's foo().

Something like:

trait Foo {   def foo() }  trait M extends Foo {   override def foo() {     println("M")     super.foo()   } }  class FooImpl1 extends Foo {   override def foo() {     println("Impl")   } }  class FooImpl2 extends FooImpl1 with M  

I tried self types and structural types, but I can't get it to work.

like image 323
IttayD Avatar asked Jan 10 '10 19:01

IttayD


People also ask

Can you override an abstract method?

An abstract method is a method that is declared, but contains no implementation. you can override both abstract and normal methods inside an abstract class. only methods declared as final cannot be overridden.

What is difference between abstract class and trait in Scala?

Abstract Class supports single inheritance only. Trait can be added to an object instance. Abstract class cannot be added to an object instance. Trait cannot have parameters in its constructors.

Can Scala traits have methods?

In scala, trait is a collection of abstract and non-abstract methods. You can create trait that can have all abstract methods or some abstract and some non-abstract methods. A variable that is declared either by using val or var keyword in a trait get internally implemented in the class that implements the trait.

What is difference between overriding and abstract class?

An abstract method is a contract which forces its immediate subclass to implement the behaviour of all abstract methods. Where as overriding is optional and is not always a necessity for the subclasses. Efficiency of abstract method lies in the fact that they force the immediate subclass to provide implementation.


1 Answers

You were very close. Add the abstract modifier to M.foo, and you have the 'Stackable Trait' pattern: http://www.artima.com/scalazine/articles/stackable_trait_pattern.html

trait Foo {   def foo() }  trait M extends Foo {   abstract override def foo() {println("M"); super.foo()} }  class FooImpl1 extends Foo {   override def foo() {println("Impl")} }  class FooImpl2 extends FooImpl1 with M 
like image 124
retronym Avatar answered Oct 20 '22 07:10

retronym