简体   繁体   中英

What does => mean at the beginning of a Scala class definition?

The author of the question Exchanging type parameters with abstract types wrote a => at the beginning of his class definitions. Example:

abstract class Thing { t => 
  type A 
  type G <: Group { type A = t.A } 
  val group: G 
} 

What does the t => mean ?

Because this is hard to find in Google & Co, can someone please give me more background information or provide a link, where I can find more information about this language construct ?

The default naming for class itself is this . You may replace it with t by t =>

It is useful if your class contains subclasses and you need access to enclosing self reference.

Without t => in your example you would write something like this:

abstract class Thing {
  type G <: Group { type A = this.A }
}

Group { type A = this.A } is a subtype so this would reference to group specialization itself not to a thing object. Probably you get not what you mean to get. If you need access to Thing self reference you should resolve name conflict by assigning self reference another name

abstract class Thing { another_this = >
  type G <: Group { type A = another_this.A}
}

It is indeed self type annotation. See the official Scala specification:

https://scala-lang.org/files/archive/spec/2.13/13-syntax-summary.html

According to this specification, its context free EBNF syntax is:

SelfType ::= id [':' Type] '=>' | 'this' ':' Type '=>' So, basically, this means SelfType has two basic forms. In one form, you can use an id with or without Type. In the other, you can use this but it must be accompanied with a Type.

You can find it in section 29.4 of Programming in Scala Second Edition. However, remember that books can be quickly out of date, so you need to refer to the specification.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM