类型参数规避匹配穷举警告

Type parameter circumvents match exhaustivity warning

为什么密封类型绑定的类型参数似乎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 {
    ^

模式匹配

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

是否详尽取决于 T

T <: A 并不意味着 TBC,请参阅 )。

根据specification

If the selector of a pattern match is an instance of a sealed class, the compilation of pattern matching can emit warnings which diagnose that a given set of patterns is not exhaustive, i.e. that there is a possibility of a MatchError being raised at run-time.

因此编译器 可以 必须 发出警告。