【问题标题】:Type parameter circumvents match exhaustivity warning类型参数规避匹配穷举警告
【发布时间】:2020-05-19 11:58:43
【问题描述】:

为什么被密封类型绑定的类型参数似乎not 会引发穷举警告

sealed trait A
case class B() extends A
case class C(i: Option[Int]) extends A

def f[T <: A](a: T) =
  a match {
    case B() =>
    case C(None) =>
  }

f(C(Some(42))) // throws MatchError

虽然没有类型参数

def f(a: A) =
  a match {
    case B() =>
    case C(None) =>
  }

发出警告

warning: match may not be exhaustive.
It would fail on the following input: C(Some(_))
    a match {
    ^

【问题讨论】:

  • 听起来像个错误。

标签: scala pattern-matching compiler-warnings type-parameter non-exhaustive-patterns


【解决方案1】:

模式匹配

def f[T <: A](a: T) =
  a match {
    case B() =>
    case C(None) =>
  }

取决于T,可以是详尽的或不详尽的。

T &lt;: A 并不意味着TBC,请参阅123)。

根据specification

如果模式匹配的选择器是密封类的实例,模式匹配的编译会发出警告,诊断给定的模式集并不详尽,即MatchError 可能存在在运行时引发。

所以编译器可以但不是必须发出警告。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-22
    • 1970-01-01
    • 1970-01-01
    • 2016-08-10
    • 2018-09-18
    • 2011-09-09
    • 1970-01-01
    • 2013-02-10
    相关资源
    最近更新 更多