Search code examples
scalatype-systems

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


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[-] {}