在试图理解一些代码时,我遇到了奇怪的行为并将其简化为:
在匹配中引入类型参数不起作用:
scala> Some(0) match { case _: Some[A] => 0 }
<console>:8: error: not found: type A
Some(0) match { case _: Some[A] => 0 }
^
但是,如果我把它变成小写,它会:
scala> Some(0) match { case _: Some[a] => 0 }
res2: Int = 0
这是 Scala 中的错误还是我缺少解释?
最佳答案
您可以在模式中使用值变量看到相同的内容:
scala> Some(0) match { case A => 0 }
<console>:8: error: not found: value A
Some(0) match { case A => 0 }
^
scala> Some(0) match { case a => 0 }
res1: Int = 0
如果你想在模式中引入一个变量(在值或类型级别),你必须使用小写标识符——根本没有办法引入大写变量。请注意,可以采用另一个方向——如果您想匹配小写变量的值,可以用反引号将其括起来。
来自 the language specification (讨论 2.3 中引入的更改):
The syntax of types in patterns has been refined (§8.2). Scala now distinguishes be- tween type variables (starting with a lower case letter) and types as type arguments in patterns. Type variables are bound in the pattern. Other type arguments are, as in previous versions, erased.
所以不,不是错误,尽管它可以说是一个非常令人困惑的语言设计决策。
关于scala - 类型变量只能在匹配中引入,如果它是小写的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21525563/