scala - 类型变量只能在匹配中引入,如果它是小写的?

标签 scala generics

在试图理解一些代码时,我遇到了奇怪的行为并将其简化为:

在匹配中引入类型参数不起作用:

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/

相关文章:

scala - 2 不同类中具有相同名称的扩展方法在 Scala 3 中不起作用?

scala - Spring MVC 现在完全支持 Scala 了吗?

c# - 是否可以创建具有通用事件的类?

c# - 从 List<T> 继承的类型不能分配给 List<T>

scala - future 的值(value)取决于它是否已经绑定(bind)到一个变量?

list - Scala:如何使用多个分隔符进行分割

java 到 scala 的转换 - r 树的通用类型丢失了?

java - 有什么方法可以创建一个通用列表,在其中添加类型和子类型?

arrays - SWIFT - 如何获取数组的类型?

scala - 尽管优先考虑了隐式,为什么我会收到 "ambiguous implicits"错误?