Avoid scala inheritance method

The following code snippet

class A {
   def foo = "A.foo"
}

trait B {
   def foo = "B.foo"
   def bar = "B.bar"
}

val x = new A with B

not compiled because

error: overriding method foo in class A of type => java.lang.String;
method foo in trait B of type => java.lang.String needs `override' modifier

However, my intention is defined as follows:

x.foo => "A.foo"
x.bar => "B.par"

That is, I want x to inherit the bar from B, but not foo. Is there a way in scala to achieve this?

+3
source share
2 answers
scala> val x = new A with B { override def foo = super[A].foo }
x: A with B = $anon$1@4822f558

scala> x.foo
res0: java.lang.String = A.foo

scala> x.bar
res1: java.lang.String = B.bar

This is clearly not what you want to do too often.

+12
source

It seems to you that you really do not want to A with Bbe B, but have access to a subset of the behavior B, this sounds like a good example for composition over inheritance

class A(val b: B) {
   def foo = "A.foo"
   def bar = b.bar
}

class B {
   def foo = "B.foo"
   def bar = "B.bar"
}

val x = new A(new B)
x.foo => "A.foo"
x.bar => "B.bar"

, A B , bar , :

class A {
  def foo = "A.foo"
}
class B {
  def foo = "B.foo"
  def bar = "B.bar"
}

implicit def a2b(a: A) = new B

val x = new A
x.foo => "A.foo"
x.bar => "B.bar"
+5

All Articles