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 ?
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 => ).
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With