首页 > 解决方案 > 为什么使用 SBT 编译时会出现此错误?

问题描述

像这样:

unreachable code due to variable pattern

错误信息

我知道如何解决它,但我不知道为什么?是编译器的bug?

标签: scala

解决方案


理解的关键是给出一系列模式,然后第一个匹配的模式获胜,其余的被忽略

匹配表达式是通过按写入顺序尝试每个模式来评估的。选择第一个匹配的模式,然后选择并执行箭头后面的部分。

例如,考虑下面匹配任何值的变量模式 pattern2

(42: Any) match {
  case pattern1: String => "first pattern1 was tried but did not match"
  case pattern2         => "then pattern2 was tried and it did indeed match"
  case pattern3: Int    => "so pattern3 was not tried because pattern2 already won"
}

thenpattern3将永远不会被尝试,并且整个匹配表达式的计算结果为

then pattern2 was tried and it did indeed match

而编译器发出警告

Warning:(19, 28) unreachable code due to variable pattern 'pattern2' on line 22
  case pattern3: Int    => "so pattern3 was not tried because pattern2 already won"

这不是错误,而只是指定编译器的工作方式,以避免永远不会执行的错误或无法访问的代码。另一种思考方式是将模式匹配想象成一个if-elses链

if (cond1) {
  "first cond1 was tried but did not match"
} else if (cond2) {
  "then cond2 was tried and it did indeed match"
} else if (cond3) {
  "so cond3 was not tried because cond2 already won"
} else {
  // crash
}

推荐阅读