如果在多个列表中循环但在 Scala 中一个为空会发生什么
what happens if looping within several list but one is empty in Scala for
我有一个像这样的 Scala 循环:
for {
players <- Players.getAll(p => p.age > 4)
salaries <- Salaries.getAll(s => s.amount > 30000)
}yield {
/*other stuff to do*/
....
}
发生什么事只是球员之一或薪水是空的? other stuff to do 处的代码会被执行吗?循环就不会执行吗?
会发生什么
我重新格式化您的代码以使其更清晰:
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
works applying a function that returns a sequence for each element in the list, and flattening the results into the original list.
没有列表元素 - 没有应用函数。这意味着 /*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)
我有一个像这样的 Scala 循环:
for {
players <- Players.getAll(p => p.age > 4)
salaries <- Salaries.getAll(s => s.amount > 30000)
}yield {
/*other stuff to do*/
....
}
发生什么事只是球员之一或薪水是空的? other stuff to do 处的代码会被执行吗?循环就不会执行吗?
会发生什么
我重新格式化您的代码以使其更清晰:
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
works applying a function that returns a sequence for each element in the list, and flattening the results into the original list.
没有列表元素 - 没有应用函数。这意味着 /*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)