我需要在for循环中创建一个列表,而我在执行它时遇到了麻烦。
我曾经使这段代码运行良好:
val tasksSchedules = orders.map (order => {
// Creates list of TaskSchedules
order.Product.Tasks.map(task => {
// Create TaskSchedule
})
})
然而,出现了一个新的要求,我现在需要根据数量重复创建TaskSchedule列表。我现在有以下代码:
val tasksSchedules = orders.map (order => {
// Repeats creation of TaskSchedules as many times as the value of Quantity
// Creation of list is lost with this for.
for (i <- 1 to order.Quantity) {
// Creates list of TaskSchedules
order.Product.Tasks.map(task => {
// Create TaskSchedule
})
}
})
没有for循环,一切都无缝地工作。但是,使用for循环没有创建我认为可以预期的列表。本质上,我需要一个for循环结构,它将使我能够迭代到某个值,并且行为类似于map函数,所以我也可以创建一个列表。
有这样的事吗?这可行吗?
答案 0 :(得分:2)
当你进行for循环时,为了生成一个列表,你需要使用 yield 命令:
val tasksSchedules = orders.map (order => {
// Repeats creation of TaskSchedules as many times as the value of Quantity
// Creation of list is lost with this for.
for (i <- 1 to order.Quantity) yield {
// Creates list of TaskSchedules
order.Product.Tasks.map(task => {
// Create TaskSchedule
})
}
})
在这种情况下,它会为您提供列表清单列表。
如果您只需要列表列表,请使用flatmap而不是map。
答案 1 :(得分:2)
对于它的价值,只需将for-comprehension重写为map()
次调用即可。您可以使用map()
s简单地重写它,而不是当前的实现(IMO,不一致),而不是:#/ p>
val tasksSchedules = orders.map { order =>
// Repeats creation of TaskSchedules as many times as the value of Quantity
// Creation of list is lost with this for.
(1 to order.Quantity).toSeq.map { i =>
// Creates list of TaskSchedules
order.Product.Tasks.map { task =>
// Create TaskSchedule
}
}
}
或仅仅是为了理解:
val tasksSchedules = for (order <- orders) yield {
// Repeats creation of TaskSchedules as many times as the value of Quantity
// Creation of list is lost with this for.
for (i <- (1 to order.Quantity).toSeq) yield {
// Creates list of TaskSchedules
for (task <- order.Product.Tasks) yield {
// Create TaskSchedule
}
}
}