本文介绍了Java / Scala中的非短路逻辑(布尔)运算符有很好的用途吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近发现Java(和Scala)包含非短路逻辑运算符& | ,和 ^ 。我以前认为这些只能作为按位运算符。虽然可能存在 ^ 的争论,但我想不出使用非短路逻辑运算符的非常好的理由 - 虽然可以肯定,我可以设想一个例子。

I recently discovered that Java (and Scala) include non-short-circuiting logical operators &, |, and ^. I previously thought these only worked as bitwise operators. While maybe there is an argument for ^, I can't think of very good reasons for using non-short-circuiting logical operators--although sure, I can contrive an example.

这些运营商有用吗?它们似乎更容易导致难以捕获的错误。

Are these operators useful? They seem more likely to cause hard-to-catch bugs.

scala> def foo = {
     |   println("foo")
     |   true
     | }
foo: Boolean

scala> def bar = {
     |   println("bar")
     |   true
     | }
bar: Boolean

scala> foo || bar
foo
res5: Boolean = true

scala> foo | bar
foo
bar
res6: Boolean = true


推荐答案

如果右侧是您想要执行的副作用的函数(例如日志记录),它们将非常有用。但是,我会建议这有点代码味道,对下一个人来说肯定是不直观的。

They're useful if the right-hand side is a function with side-effects that you want to execute regardless (e.g. logging). However, I would suggest that that's a bit of a code smell and will certainly be unintuitive to the next guy.

这篇关于Java / Scala中的非短路逻辑(布尔)运算符有很好的用途吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 21:43