英文:
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 <- myVars
if checkSomething(x)
} yield doSomething(x)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论