我有一个Scala循环,如:
for {
players <- Players.getAll(p => p.age > 4)
salaries <- Salaries.getAll(s => s.amount > 30000)
}yield {
/*other stuff to do*/
....
}
会发生什么情况,玩家或工资之一为空? 其他要做的事情中的代码是否将被执行?会不会执行循环?
会发生什么
答案 0 :(得分:2)
我重新格式化您的代码以使其更清晰:
val pIn = Players.getAll(p => p.age > 4)
val sIn = Salaries.getAll(s => s.amount > 30000)
for {
players <- pIn
salaries <- sIn
}yield {
/*other stuff to do*/
....
}
它翻译成
pIn.flatMap(players => sIn.flatMap(salaries => { /*other stuff to do*/...}))
我们知道
flatMap
的工作原理是应用一个函数,该函数返回列表中每个元素的序列,并将结果展平到原始列表中。
没有列表元素-没有应用功能。这意味着在/*other stuff to do*/
或pIn
为空的情况下sIn
代码将不会运行
注意
pIn
或sIn
为空。这个很重要。如果players
或salaries
为空,则/*other stuff to do*/
将起作用。
这不起作用:
val pIn = List.empty
val sIn = List(1,2,3)
这将起作用:
val pIn = List(List.empty)
val sIn = List(1,2,3)