You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将foreach代码重构为yield实现——Scala新手技术求助

Refactoring Scala foreach Nests to For-Comprehension with Yield

Hey there! Let's turn that nested foreach mess into clean, idiomatic Scala using a for-comprehension with yield. I'll walk through this so it's clear for a new Scala developer.

First, let's recap what your original code is trying to do:

  • Grab the first element of col2 as tempA, then work with the remaining elements in collect
  • Iterate over each tmpCol from orderCol(collect)
  • Loop through values of a (0-9) and b (0-11)
  • Build a tmpBuild instance using those values
  • If the instance passes the isFiltered check, create a new sorted list by prepending tmpBuild to tmpCol

The problem with the original foreach approach is that it computes those sorted lists but doesn't capture or save them. A for-comprehension with yield fixes this by automatically collecting all valid results into a usable collection.

Here's the refactored code:

case _ => {
  val tempA = col2.head
  val collect = col2.drop(1)

  // Use for-comprehension to collect all valid sorted lists
  val filteredSortedLists = for {
    tmpCol <- orderCol(collect)
    a <- 0 until 10
    b <- 0 until 12
    tmpBuild = TmpBuilder.build(tempA, b, a)
    if isFiltered(tmpBuild, tmpCol) // Only keep results that pass the filter
  } yield (tmpBuild :: tmpCol).sortBy(r => (r.tempA, r.B))

  // Now you can use filteredSortedLists however you need—print it, process it, etc.
  // For example, if you still need to perform an action on each element:
  filteredSortedLists.foreach { sortedList =>
    // Do something with each sorted list here, e.g. log, save, etc.
  }
}

Key Notes:

  • The for-comprehension replaces all three nested foreach calls with a flat, readable structure that's easier to follow
  • yield collects every sorted list that passes the isFiltered check into filteredSortedLists—the type will match whatever orderCol(collect) returns (e.g., if it's a List, this will be a List[List[YourType]])
  • We moved the filter condition directly into the for-comprehension using if, which is more idiomatic than wrapping it in a block inside the loop
  • If you originally intended to perform a side effect (like printing each sorted list) instead of collecting results, you can still do that by adding a foreach on the final collection, as shown above.

内容的提问来源于stack exchange,提问作者user4399595

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:07:34