Search code examples
scalaexistential-type

Existential type at declaration site


I was playing around with Scala when I found that this compiles:

class Foo[_]

What does an existential type in a class declaration do?


Solution

  • This is legal because of following part of the grammar (given in the Scala specification):

    TmplDef ::= ‘class’ ClassDef
    ClassDef ::= id [TypeParamClause] {Annotation}
      [AccessModifier] ClassParamClauses ClassTemplateOpt
    TypeParamClause ::= ‘[’ VariantTypeParam {‘,’ VariantTypeParam} ‘]’
    VariantTypeParam ::= {Annotation} [‘+’ | ‘-’] TypeParam
    TypeParam ::= (id | ‘_’) [TypeParamClause] [‘>:’ Type] [‘<:’ Type] [‘:’ Type]
    

    I believe _ simply ends up being a type parameter name (which isn't actually usable in the class body), not part of existential type syntax.