John Threepwood
John Threepwood

Reputation: 16143

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 ?

Upvotes: 14

Views: 1560

Answers (3)

Iulian Dragos
Iulian Dragos

Reputation: 5712

this is in scope inside the body of a class, so in that sense it is a parameter (though we never think of it that way). The self-type syntax simply makes it explicit, and allows one to give it a different name (and type). So the arrow becomes a very good choice as a separator between the binder and its scope.

Upvotes: 0

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297185

Note that self isn't a keyword, but a normal identifier. You can really write any other valid identifier in place of self. And : after an expression is a type ascription, something entirely valid anywhere an expression is valid.

The => is what tells Scala there is a self-type. Otherwise, self: Type looks like a simple statement, an expression. For example:

class A
class B extends A {
  this: A
}

That is valid Scala code, and it does not have a self type.

Upvotes: 10

0__
0__

Reputation: 67280

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.

Upvotes: 11

Related Questions