1

Say I have two traits (A and B) and a class C which mixes them in and implements their methods:

trait A { def foo } trait B { def bar } class C extends A with B { def foo = "Foo" def bar = "Bar" } 

Is there any way in Scala to specify that the class that extends trait B must extend trait A and then use the implemented method of trait A's defined method in trait B?

So that B could call this.foo() and access the value that has been returned by C's implementation?

1 Answer 1

6

Just specify what you want this to be:

trait B { this: A => def bar = this.foo } 

This is so called self type and this here is an alias rather than keyword (so self: A, that: A and so on are perfectly legal).

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

2 Comments

A note aside: It often raises some confusion that the self type is not part of the public API of B. I.e. if you have an instance of B, you won't be able to call foo on it.
Is the inaccessibility of foo from outside the only difference with trait B extends A ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.