将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
col2astempA, then work with the remaining elements incollect - Iterate over each
tmpColfromorderCol(collect) - Loop through values of
a(0-9) andb(0-11) - Build a
tmpBuildinstance using those values - If the instance passes the
isFilteredcheck, create a new sorted list by prependingtmpBuildtotmpCol
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
foreachcalls with a flat, readable structure that's easier to follow yieldcollects every sorted list that passes theisFilteredcheck intofilteredSortedLists—the type will match whateverorderCol(collect)returns (e.g., if it's aList, this will be aList[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
foreachon the final collection, as shown above.
内容的提问来源于stack exchange,提问作者user4399595
相关产品推荐
相关产品推荐

