Question about features

What is the difference between the following two?

one #

trait B extends A { } 

2 #

 trait B { self: A => } 

where A is an abstract class.

β†’ EDIT:

Please explain in relation to the following Duck example with plug-in flight and quack behavior:

 abstract class Duck { def fly(): Unit def quack(): Unit def swim() { println("Woodoowoodoowoodoo...") } } trait FlyingWithWings extends Duck { override def fly() { println("Me can fliez! :D") } } trait FlyingNoWay { self: Duck => def fly() { println("Me cannot fliez! :(") } } trait Quack extends Duck { override def quack() { println("Quack! Quack!") } } trait MuteQuack { self: Duck => def quack() { println("<< Silence >>") } } class MallardDuck extends Duck with FlyingWithWings with MuteQuack object Main { def main(args: Array[String]) { val duck = new MallardDuck duck.fly() duck.quack() } } 

Output:

I can fly !: D <Silence β†’

+7
scala traits
source share
2 answers

In the second case, B cannot be used in places where A is expected, it is just designed to bind to a specific A. So, for example, in the first case, A can be abstract, and B can implement missing methods, which makes it clear. This is not possible in the second case, you need "full A", and only then will you add some functions.

So, you can think of the relationship "fits into ..." instead of the relationship "is ...".

+5
source share

In the first example, B is a specialization of A The second means that trait B must always be mixed with something that is or is a subtype, A (which can be a class, trait, or any other type).

+1
source share

All Articles