Existential type on ad site

I was playing around with Scala when I found this compile:

class Foo[_]

      

What does an existence type do in a class declaration?

+3


source to share


2 answers


This is legal because of the 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 it _

just ends up being the type parameter name (which is not actually used in the class) and not part of the existential type syntax.

+4


source


Not sure, but it looks like it's equivalent to:

scala> class Foo[T >: Nothing <: AnyRef]
defined class Foo

      

You just can't access T

. This can be confirmed by compiling with -Xprint:all

. They both generate the same AST.



Play around:

scala> new Foo
res3: Foo[Nothing] = Foo@de0a01f

scala> new Foo[String]
res4: Foo[String] = Foo@47fd17e3

scala> class Foo2[_]
defined class Foo2

scala> new Foo2[String]
res5: Foo2[String] = Foo2@2d6e8792

      

+4


source







All Articles