Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why `trait X { def append[-](): Unit }` compiles?

From the bottom of this answer: https://stackoverflow.com/a/23374938/342235, there is some code which looks strange:

trait X { 
  def append[-](): Unit 
}

Why it can be compiled? I mean the [-] is strange

like image 892
Freewind Avatar asked Mar 19 '23 17:03

Freewind


1 Answers

It is strange, but in this context - is a acceptable identifier for a type parameter. Here is a longer example:

class Y {
  def identity[-](x: -): - = x
}
(new Y).identity(5) // returns 5

The - inside [-] here is a normal type name, just like the - as the class name in the following code:

class -

Note that because the type parameters of methods cannot be marked contravariant the compiler will not interpret the - as indicating contravariance. On the other hand this will not parse:

class Z[-] {}
like image 94
wingedsubmariner Avatar answered Mar 29 '23 05:03

wingedsubmariner