Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the reason behind the `=>` in a self type?

A self type looks like the following example:

trait A { self: String => }

This says, that trait A (or a subtype of it) must inherit the class String.

The keyword self is followed by : analogue to a variable in var s: String, where the type comes after :.

But what does the => state for in a self type ? What is the reason behind this ?

like image 573
John Threepwood Avatar asked Jun 30 '12 20:06

John Threepwood


People also ask

What is a self type?

A self-type is a way to narrow the type of this or another identifier that aliases this . The syntax looks like normal function syntax but means something entirely different. To use a self-type in a trait, write an identifier, the type of another trait to mix in, and a => (e.g. someIdentifier: SomeOtherTrait => ).

What is the study of self?

the study of something by oneself, as through books, records, etc., without direct supervision or attendance in a class: She learned to read German by self-study. the study of oneself; self-examination. adjective.

What is the type of self python?

Python3. Self is a convention and not a Python keyword . self is parameter in Instance Method and user can use another parameter name in place of it. But it is advisable to use self because it increases the readability of code, and it is also a good programming practice.

How do you use traits in Scala?

In scala, trait is a collection of abstract and non-abstract methods. You can create trait that can have all abstract methods or some abstract and some non-abstract methods. A variable that is declared either by using val or var keyword in a trait get internally implemented in the class that implements the trait.


1 Answers

Just guess work... You need some specific delimiter of the self-type declaration. Imagine the => was just omitted. this: String would be a syntactically valid statement (although the type checker will complain).

So which should be the delimiter? You wouldn't want nested braces like trait A { self: String { ... }}. So which non-paired existing delimiters exist? => is the only one that I can think of.

Where is => used elsewhere? As sugar for function types (A => B) and for function bodies (i: Int => i + 1). Also for call-by-name arguments, and for the cases of a pattern match. This last usage is somewhat coherent with the self-type. It's like matching this to be of a particular type, and then defining the body depending on this 'match'. I don't know, maybe this is a silly analogy.

like image 192
0__ Avatar answered Sep 20 '22 21:09

0__