scala - 为未使用的变量使用占位符时出现 MatchError

标签 scala null pattern-matching unused-variables scala-2.13

使用 Scala 2.13.x,我得到 scala.MatchError: null当我为未使用的变量使用占位符时:

scala> object Test {
     |   val _: Any = null
     | }
object Test

scala> Test
scala.MatchError: null
  ... 41 elided
但是对于 Scala 2.12.x,我没有得到 scala.MatchError: null :
scala> object Test {
     |   val _: Any = null
     | }
defined object Test

scala> Test
res1: Test.type = Test$@784c5ef5
任何原因?

最佳答案

scala 2.13 release notes 中所述:

  • Underscore is no longer a legal identifier unless backquoted (bug#10384)
    • val _ = is now a pattern match (and discards the value without incurring a warning)
  • Make extractor patterns null safe. (#6485)
    • null is treated as no match.

当将两者结合起来时,我们可以看到这在 Scala 2.13 的设计中是不可能的。有关更多信息,您可以在实现这两个功能的 github 上的拉取请求中阅读:
下划线不再是合法标识符,除非反引号 - https://github.com/scala/bug/issues/10384
使提取器模式为空安全 - https://github.com/scala/scala/pull/6485

关于scala - 为未使用的变量使用占位符时出现 MatchError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63701707/

相关文章:

java - 如何在freemarker中检查空列表

Python 使用正则表达式捕获字符串中的特定模式

haskell - Haskell 中的类型匹配

ios - MPMediaItemArtwork 为空,而封面在 iTunes 中可用

haskell - 从包装器中动态匹配嵌套的 GADT

mongodb - 如何在结构化流中处理 JSON 文档(来自 MongoDB)并写入 HBase?

scala - 如何从DataFrame中获取Array[Seq[String]]?

java - 使用play-framework 2.5连接MySQL数据库

scala - 从Java继承时如何在Scala中引用 protected 内部类(仅限字节码)

C strchr 在 HPUX 上使用 NULL 值,但在 RHEL 上出现段错误