Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between trait inheritance and self type annotation

In Scala, I've seen the constructs

trait T extends S 

and

trait T { this: S => 

used to achieve similar things (namely that the abstract methods in S must be defined before an instance may be created). What's the difference between them? Why would you use one over the other?

like image 729
Ben Lings Avatar asked Feb 08 '10 21:02

Ben Lings


People also ask

What does self => mean in Scala?

It lets you create dependencies among modules. For instance: class System extends Base with CompA with CompB with CompC. If CompA needs to use something from CompC , it can be defined as: trait CompA { self: CompC => ... } In this case: class System extends Base with CompA with CompB.

What are self types?

Self-types are a way to declare that a trait must be mixed into another trait, even though it doesn't directly extend it. That makes the members of the dependency available without imports. A self-type is a way to narrow the type of this or another identifier that aliases this .

What is the difference between class and trait?

Trait supports multiple inheritance. Abstract Class supports single inheritance only. Trait can be added to an object instance. Abstract class cannot be added to an object instance.

What is trait in spark?

A trait encapsulates method and field definitions, which can then be reused by mixing them into classes. Unlike class inheritance, in which each class must inherit from just one superclass, a class can mix in any number of traits.


1 Answers

Self type annotations allow you to express cyclic dependencies. For instance:

trait A extends B trait B { self: A => } 

This is not possible with simple inheritance.

like image 155
Joa Ebert Avatar answered Sep 24 '22 15:09

Joa Ebert