斯卡拉的||和 |运营商
Scala's || and | operators
我今天注意到一件事。 Scala 有通常的 OR ||
,还有 |
.
我的第一个想法是 |
是一个严格的 OR。所以 true | true
,将计算为 false
。
但是,
val x = true
x: Boolean = true
val y = true
y: Boolean = true
x || y
res4: Boolean = true
x | y
res5: Boolean = true
|
运算符有什么用?它只是一个别名吗?
与 Java 一样,单个 &
和 |
运算符与它们通常的版本做同样的事情,但没有 short-circuiting.
例如,考虑表达式 true || isNice()
。该方法将永远不会被调用,因为 true || x
始终为真并且编译器(和运行时)知道这一点。如果您坚持要评估布尔表达式的所有部分,则必须使用 &
或 |
。
编辑:为了完整起见,Scala 还使用 |
作为模式匹配中的替代模式。这是从语言参考中复制的:
8.1.11 Pattern Alternatives
Syntax:
Pattern ::= Pattern1 { ‘|’ Pattern1 }
A pattern alternative p1 | ... | pn consists of a number of alternative patterns
pi
. All alternative patterns are type checked with the expected type of the pattern.
They may no bind variables other than wildcards. The alternative pattern matches
a value v if at least one its alternatives matches v.
我今天注意到一件事。 Scala 有通常的 OR ||
,还有 |
.
我的第一个想法是 |
是一个严格的 OR。所以 true | true
,将计算为 false
。
但是,
val x = true
x: Boolean = true
val y = true
y: Boolean = true
x || y
res4: Boolean = true
x | y
res5: Boolean = true
|
运算符有什么用?它只是一个别名吗?
与 Java 一样,单个 &
和 |
运算符与它们通常的版本做同样的事情,但没有 short-circuiting.
例如,考虑表达式 true || isNice()
。该方法将永远不会被调用,因为 true || x
始终为真并且编译器(和运行时)知道这一点。如果您坚持要评估布尔表达式的所有部分,则必须使用 &
或 |
。
编辑:为了完整起见,Scala 还使用 |
作为模式匹配中的替代模式。这是从语言参考中复制的:
8.1.11 Pattern Alternatives Syntax: Pattern ::= Pattern1 { ‘|’ Pattern1 }
A pattern alternative p1 | ... | pn consists of a number of alternative patterns pi . All alternative patterns are type checked with the expected type of the pattern. They may no bind variables other than wildcards. The alternative pattern matches a value v if at least one its alternatives matches v.