【问题标题】:Warning Match may not be exhaustive警告匹配可能并不详尽
【发布时间】:2018-12-20 07:22:58
【问题描述】:

我正在尝试以下代码:

  val set1 = Set(1,2,3,4,5,67,8)
  val TRUE_BOOLEAN = true
  val FALSE_BOOLEAN = false
  set1.contains(4) match {
    case TRUE_BOOLEAN => println("Element found")
    case FALSE_BOOLEAN => println("Element not found")
  }

但是,当我尝试在IntelliJ 中运行它时,它在Messages 选项卡中给出以下警告:

Warning:(11, 16) match may not be exhaustive.
It would fail on the following inputs: false, true
  set1.contains(4) match {

然而,如果我使用 truefalse 而不是 TRUE_BOOLEANFALSE_BOOLEAN,我不会收到任何警告。

set1.contains(4) match {
    case true => println("Element found")
    case false => println("Element not found")
  }

谁能解释这个警告的原因以及为什么它会随着truefalse消失。

【问题讨论】:

  • 即使我明确指定类型,我仍然会收到警告。无论类型注释是否存在,Scastie 也会给出相同的警告。不可重现。考虑将其明确重新标记为 intellij-bug。
  • @Yogesh 这与您的提议有何相同之处?
  • @AndreyTyukin 如提到的重复 URL,in pattern matching you should account for all possible cases or provide a "fallback" 如果您在匹配中添加 case _,则不会显示警告。
  • @AndreyTyukin 是的,你是对的......即使在明确添加类型后我也会收到警告。我将编辑我的问题。

标签: scala pattern-matching


【解决方案1】:

它会产生警告,因为它不能保证匹配是详尽的。

确实,当嵌入到正确的上下文中时,您的代码会在运行时引发匹配错误:

class Foo {
  val set1 = Set(1,2,3,4,5,67,8)
  val TRUE_BOOLEAN = true
  val FALSE_BOOLEAN = false
  set1.contains(4) match {
    case TRUE_BOOLEAN => println("Element found")
    case FALSE_BOOLEAN => println("Element not found")
  }
}

class Bar extends Foo {
  override val TRUE_BOOLEAN = false
}

new Bar // scala.MatchError: true (of class java.lang.Boolean)

所以警告是正确,而不仅仅是一个过于保守的估计。由于每个 Scala 脚本都隐式嵌入到一些“类类”包装器中,因此它在 Scala 脚本中也以完全相同的方式工作,即使您没有将其包装在 Foo-class 中。

如果您将两个变量都设置为final,则常量传播可以正常工作,并且不会发出警告:

class Foo {
  val set1 = Set(1,2,3,4,5,67,8)
  final val TRUE_BOOLEAN = true
  final val FALSE_BOOLEAN = false
  set1.contains(4) match {
    case TRUE_BOOLEAN => println("Element found")
    case FALSE_BOOLEAN => println("Element not found")
  }
}

编译正常,没有警告。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多