scala if 语句的否定条件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40070210/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Negate condition of an if-statement
提问by Jeff Hu
If I want to do something like:
如果我想做类似的事情:
if (!(condition)) { }
What is the equivalent expression in Scala? Does it looks like?
Scala 中的等价表达式是什么?看起来像吗?
if (not(condition)) { }
For example, in C++, I can do:
例如,在 C++ 中,我可以这样做:
bool condition = (x > 0)
if(!condition){ printf("x is not larger than zero") }
EDIT: I have realized that Scala can definitely do the same thing as I asked. Please go ahead and try it.
编辑:我已经意识到 Scala 绝对可以像我问的那样做同样的事情。请继续尝试。
回答by jrbedard
In Scala, you can check iftwo operands are equal (==) or not (!=) and it returns true if the condition is met, false if not (else).
在 Scala 中,您可以检查if两个操作数是否相等 ( ==) 或不相等 ( ) !=,如果满足条件则返回真,否则返回假 ( else)。
if(x!=0) {
// if x is not equal to 0
} else {
// if x is equal to 0
}
By itself, !is called the Logical NOT Operator. Use it to reverse the logical state of its operand. If a condition is true then Logical NOT operator will make it false.
就其本身而言,!称为逻辑非运算符。使用它来反转其操作数的逻辑状态。如果条件为真,则逻辑非运算符将使其为假。
if(!(condition)) {
// condition not met
} else {
// condition met
}
Where conditioncan be any logical expression. ie: x==0to make it behave exactly like the first code example above.
wherecondition可以是任何逻辑表达式。即:x==0使其行为与上面的第一个代码示例完全相同。
回答by pamu
if (! condition) { doSomething() }
if (! condition) { doSomething() }
conditionin the above ifexpression can be any expression which evaluates to Boolean
condition在上面的if表达式中可以是任何计算结果为Boolean
for example
例如
val condition = 5 % 2 == 0
if (! condition) { println("5 is odd") }
!=is equivalent to negation of ==
!=相当于 negation of ==
if (x != 0) <expression> else <another expression>
Scala REPL
Scala REPL
scala> if (true) 1
res2: AnyVal = 1
scala> if (true) 1
res3: AnyVal = 1
scala> if (true) 1 else 2
res4: Int = 1

