Question

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

Was it helpful?

Solution

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[-] {}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top