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

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

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

问题

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

  1. val myVar1 = myObj.getMyVar1()
  2. val myVar2 = myObj.getMyVar2()
  3. val myVar3 = myObj.getMyVar3()
  4. val myVar4 = myObj.getMyVar4()
  5. if (checkSomething(myVar1)) {
  6. dosomething(myVar1)
  7. }
  8. if (checkSomething(myVar2)) {
  9. dosomething(myVar2)
  10. }
  11. if (checkSomething(myVar3)) {
  12. dosomething(myVar3)
  13. }
  14. if (checkSomething(myVar4)) {
  15. dosomething(myVar4)
  16. }
英文:

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

  1. val myVar1 = myObj.getMyVar1()
  2. val myVar2 = myObj.getMyVar2()
  3. val myVar3 = myObj.getMyVar3()
  4. val myVar4 = myObj.getMyVar4()
  5. if (checkSomething(myVar1)) {
  6. dosomething(myVar1)
  7. } }
  8. if (checkSomething(myVar2)) {
  9. dosomething(myVar2)
  10. }
  11. if (checkSomething(myVar3)) {
  12. dosomething(myVar3)
  13. } }
  14. if (checkSomething(myVar4)) {
  15. dosomething(myVar4)
  16. }

答案1

得分: 2

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

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

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

  1. val list: List[_] = List(myVar1, myVar2, myVar3, myVar4)
  2. 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.

  1. val myVars = List(myVar1, myVar2, myVar3, myVar4)
  2. for {
  3. x <- myVars
  4. if checkSomething(x)
  5. } 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.

  1. val myVars = List(myVar1, myVar2, myVar3, myVar4)
  2. for {
  3. x &lt;- myVars
  4. if checkSomething(x)
  5. } 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:

确定