最新消息:20210917 已从crifan.com换到crifan.org

【已解决】scala中实现变量取反not操作

实现 crifan 796浏览 0评论
折腾:
【未解决】scala中如何实现for循环中的continue继续执行
期间,希望把复杂的breakable的代码:
for(l <- file.getLines()){
  breakable {
    if (l.trim.isEmpty){
      break()
    }
    else{
。。。
改为not判断:
用 not 去判断
scala not Operator
scala – Negate condition of an if-statement – Stack Overflow
if(!(condition)) {
    // condition not met
} else {
    // condition met
}
去写成:
if (!(l.trim.isEmpty)){
然后IntelliJ IDEA中,左右括号显示灰色
移动上去,发现提示:是多余的,建议去除:
Remove uncessary parentheses (l.trim.isEmpty)
代码变成:
if (!l.trim.isEmpty){
-》那看来是:
!感叹号后面, 不是一定要加括号
而是根据情况:本身是变量了,就不用。
如果是表达式,估计采用
-》那就和其他语言中是否要加括号,是一致的逻辑了。
Scala – Operators – Tutorialspoint
其中有:
Operator
Description
Example
&&
It is called Logical AND operator. If both the operands are non zero then condition becomes true.
(A && B) is false.
||
It is called Logical OR Operator. If any of the two operands is non zero then condition becomes true.
(A || B) is true.
!
It is called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.
!(A && B) is true.
【总结】
此处scala代码,用not,可以用:感叹号:
if (!l.trim.isEmpty){

就可以把之前breakable冗余的代码:
import scala.util.control.Breaks.{break, breakable}

for(eachLine <- file.getLines()){
  breakable {
    if (eachLine.trim.isEmpty){
      break()
    }
    else{
      println(eachLine)
    }
  }
改为精简的:
for(l <- file.getLines()){
  if (!l.trim.isEmpty){
    val row = l.split("\\|",2)
    if (row.size < 2){
      println(s"ERROR url : ${l} for ${rulePath}")
    } else {
      urlMatch.addPattern(row(0), row(1))
    }
  }
}
后记:
已回复帖子
scala – Negate condition of an if-statement – Stack Overflow

转载请注明:在路上 » 【已解决】scala中实现变量取反not操作

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
90 queries in 0.181 seconds, using 23.35MB memory