Combining if statement for multiple variable in a match case in scala

huangapple go评论50阅读模式
英文:

Combining if statement for multiple variable in a match case in scala

问题

我正在寻找一种更简洁的方式来执行以下操作的Scala代码:

val myVar1 = myObj.getMyVar1()
val myVar2 = myObj.getMyVar2()
val myVar3 = myObj.getMyVar3()
val myVar4 = myObj.getMyVar4()

if (checkSomething(myVar1)) {
    dosomething(myVar1)
}

if (checkSomething(myVar2)) {
    dosomething(myVar2)
}

if (checkSomething(myVar3)) {
    dosomething(myVar3)
}

if (checkSomething(myVar4)) {
    dosomething(myVar4)
}
英文:

I am looking for a cleaner way of doing the following operation in scala

      val myVar1 = myObj.getMyVar1()
      val myVar2 = myObj.getMyVar2()
      val myVar3 = myObj.getMyVar3()
      val myVar4 = myObj.getMyVar4()

      if (checkSomething(myVar1)) {
          dosomething(myVar1)
      }          }
      if (checkSomething(myVar2)) {
          dosomething(myVar2)
      }    
      if (checkSomething(myVar3)) {
          dosomething(myVar3)
      }          }
      if (checkSomething(myVar4)) {
          dosomething(myVar4)
      } 

答案1

得分: 2

你可以使用 List 来存储所有你的变量,然后使用 filter 和 map。

val list: List[_] = List(myVar1, myVar2, myVar3, myVar4)
list.filter(checkSomething).foreach(doSomething)
英文:

You can use List to store all your variables and then use filter and map

val list: List[_] = List(myVar1, myVar2, myVar3, myVar4)
list.filter(checkSomething).foreach(doSomething)

答案2

得分: 1

You could also use the for/yield style with guard if condition as below.

No need to mention the return type of myVars since this is Scala.

val myVars = List(myVar1, myVar2, myVar3, myVar4)

for {
  x <- myVars 
  if checkSomething(x)
} yield doSomething(x)
英文:

You could also use the for/yield style with guard if condition as below.

No need to mention the return type of myVars since this is Scala.

val myVars = List(myVar1, myVar2, myVar3, myVar4)

for {
  x &lt;- myVars 
  if checkSomething(x)
} yield doSomething(x)

huangapple
  • 本文由 发表于 2023年4月20日 06:18:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76059206.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定