0

Suppose I have next traits:

trait A { val a: String = "a" } trait B { def a: String = "b" } 

And I want to mix both of these traits into some class C

class C extends B with A

Compiler doesn't allow me to create such class because I have to override method a

I want to override it using for example only A's implementaion. How can I do this?

EDIT

scala> class C extends B with A { | override val a = super.a | } <console>:10: error: super may be not be used on value a override val a = super.a ^ 

2 Answers 2

1

The compiler can't possibly know which one you intend to use, therefore you must specify it like:

class C extends B with A { override def a = super[A].a } 

This approach allows you to choose the parent directly, regardless the trait order.

However, the traits define a differently (val and def) thus you must choose only one. You should use either def or val in both traits (not mix them).

Sign up to request clarification or add additional context in comments.

2 Comments

this will not compile
Have you unified def and val in traits? What scala version do you use?
0

Provided you make a a def in the A trait, you can do

class C extends B with A { override val a = super.a } val c = new C c.a // "a" 

This will work because A is extended after B, so super will be its implementation.

4 Comments

this will not compile
@maks, read my answer carefully. You need to make a a def in A.
in my question I provided just an example. In reality A and B is a library code
you should specify it in the question then. This makes a big difference and you cannot refer to a super value from a subclass.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.