什么是规范正确用语SimpleType [Type] [Type]?

时间:2014-12-28 16:16:58

标签: scala

在Scala规范中。 Chapter 3,写道:

  Type              ::=  FunctionArgTypes ‘=>’ Type
                      |  InfixType [ExistentialClause]
  FunctionArgTypes  ::=  InfixType
                      |  ‘(’ [ ParamType {‘,’ ParamType } ] ‘)’
  ExistentialClause ::=  ‘forSome’ ‘{’ ExistentialDcl
                             {semi ExistentialDcl} ‘}’
  ExistentialDcl    ::=  ‘type’ TypeDcl
                      |  ‘val’ ValDcl
  InfixType         ::=  CompoundType {id [nl] CompoundType}
  CompoundType      ::=  AnnotType {‘with’ AnnotType} [Refinement]
                      |  Refinement
  AnnotType         ::=  SimpleType {Annotation}
  SimpleType        ::=  SimpleType TypeArgs
                      |  SimpleType ‘#’ id
                      |  StableId
                      |  Path ‘.’ ‘type’
                      |  ‘(’ Types ‘)’
  TypeArgs          ::=  ‘[’ Types ‘]’
  Types             ::=  Type {‘,’ Type}

让我们考虑以下重写:

Type

InfixType 

CompundType 

AnnotType 

SimpleType 

SimpleType [Type] 

SimpleType [Type] [Type]

所以SimpleType [Type] [Type]似乎是一种有效的类型。至少它在这个语法中是一个有效的句子,我能理解正确吗?

是否有使用此类表达式?

换句话说,是否可以编写一个包含SimpleType [Type] [Type]并编译的Scala程序?

如果是,怎么样?如果没有,为什么不呢?

除非有效,否则有什么意义

SimpleType ::= SimpleType TypeArgs

在Scala的语法中?

1 个答案:

答案 0 :(得分:8)

Parser只是编译器阶段中的一个,所以是 - 它将语法解析为AST,但不是 - 它不会语义有效AST

解析的:

scala> val a: List[Int][Int] = null
<console>:13: error: List[Int] does not take type parameters
   val a: List[Int][Int] = null
          ^

未解析:

scala> def aaa[A][B]
<console>:1: error: '=' expected but '[' found.
   def aaa[A][B]
             ^

scala> trait A[A][B]
<console>:1: error: ';' expected but '[' found.
       trait A[A][B]
                 ^

因此,您似乎无法定义此类型,但可以参考此类型。更深层的是,scala还没有完全支持类型参数(只要是类型构造函数) - 所以现在没有对它们进行讨论,但将来可能会这样做。

更新:

实际上有一个例子,如果你调用适用的东西,这种语法实际上是有效的:

scala> object Def1 { def apply[T] = 0 }
defined object Def1

scala> object Def2 { def apply[T] = Def1 }
defined object Def2

scala> Def2[Int][Int]
res0: Int = 0

但是,仍然无法找到[A][B]内部类型定义的示例,它可能是一个为将来保留的功能。

相关问题