Scala - 明确说明定义 && 和 || 时的短路 功能

Has*_*san 3 scala short-circuiting

在 Boolean 的 Scala 源代码中(此处),据说函数 && 和 || 不能使用 => 语法定义。

// Compiler won't build with these seemingly more accurate signatures
// def ||(x: => Boolean): Boolean
// def &&(x: => Boolean): Boolean
Run Code Online (Sandbox Code Playgroud)

但我看不出这些定义有任何问题!

All*_*hou 5

源代码说不会而不是不能,可能你理解错了。

如果你看到 Boolean.scala 的第 56 行,你会发现 || 的一些解释。

此方法使用“短路”评估,其行为就像声明为def ||(x: => Boolean): Boolean. 如果a计算结果为truetrue则返回而不计算b

源代码中的 && 也是如此。综上所述,可以这样定义,但没有必要,因为短路。