Oct 6, 2009

Multiple Method Inheritance in Scala

I had a little issue today that likely crops up once in a while when using Scala's traits. I have a class with a particular method foo(), and a trait with a method of the same name. When I created a derived class that used this trait, I didn't know how to specify which version of foo() I wanted to call. Let's take a look at our picture:
class Blah{
def foo(){
}
}

trait Tleh{
def foo(){
}
}

class Dingle extends Blah with Tleh{
override def foo(){
super.foo // this calls Tleh.foo
}
}
As I mentioned in the comment there, using super.foo calls the trait's version of foo(). But what if you want to call Blah's version of foo()?

It's actually pretty simple, and a bit intuitive if you know a bit of Scala:
class Dingle extends Blah with Tleh{
override def foo(){
super.foo // calls Tleh.foo
super[Blah].foo // calls Blah.foo
super[Tleh].foo // calls Tleh.foo
}
}
This is pretty simple, but it took me a little while to figure it out since there doesn't seem to be any mention of this in the docs I found!

No comments: