加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 09:54:42 所属栏目:安全 来源:网络整理
导读:在尝试理解某些代码时,我遇到了奇怪的行为,并将其简化为: 在匹配中引入类型参数不起作用: scala Some(0) match { case _: Some[A] = 0 }console:8: error: not found: type A Some(0) match { case _: Some[A] = 0 } ^ 但是,如果我将其设为小写,它会: sca
在尝试理解某些代码时,我遇到了奇怪的行为,并将其简化为:

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

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.

所以不,不是一个错误,虽然它可以说是一个非常令人困惑的语言设计决定.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读