English 中文(简体)
Traits and abstract methods override in Scala
原标题:
  • 时间:2010-01-10 19:58:36
  •  标签:
  • 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.

最佳回答

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
问题回答

暂无回答




相关问题
How to flatten a List of different types in Scala?

I have 4 elements:List[List[Object]] (Objects are different in each element) that I want to zip so that I can have a List[List[obj1],List[obj2],List[obj3],List[obj4]] I tried to zip them and I ...

To use or not to use Scala for new Java projects? [closed]

I m impressed with Twitter and investigating to use Scala for a new large scale web project with Hibernate and Wicket. What do you think about Scala, and should I use it instead of Java? EDIT: And, ...

Why does Scala create a ~/tmp directory when I run a script?

When I execute a Scala script from the command line, a directory named "tmp" is created in my home directory. It is always empty, so I simply deleted it without any apparent problem. Of course, when I ...

Include jar file in Scala interpreter

Is it possible to include a jar file run running the Scala interpreter? My code is working when I compile from scalac: scalac script.scala -classpath *.jar But I would like to be able to include a ...

Scala and tail recursion

There are various answers on Stack Overflow which explain the conditions under which tail recursion is possible in Scala. I understand the limitations and how and where I can take advantage of tail ...

热门标签