Scala中移除isDefined的等价序列过滤实现,简化代码并获取Map[String,Seq[String]]结果
isDefined和get的使用 Got it, let's refine this Scala code to be more idiomatic and avoid the clunky isDefined + get combo while getting exactly the Map[String, Seq[String]] result you want.
原逻辑回顾
Your original code does two key things:
- Filters out elements where
xisNone - Groups the remaining elements by the value inside
x, then implicitly converts the groupedAinstances to their inner string values to reachMap[String, Seq[String]]
The problem with isDefined and get is that while they work here (since you filtered first), they're not the most idiomatic Scala—we can use Option's built-in functions to make this cleaner and safer.
优化方案1:用flatMap一步到位
This is the most concise approach. flatMap automatically ignores None values and unwraps Some values into their inner strings:
val result: Map[String, Seq[String]] = t.flatMap(_.x).groupBy(identity)
t.flatMap(_.x)takes eachAin the sequence, extracts itsx(anOption[String]), and flattens the sequence—soNoneentries disappear, andSome("abc")becomes just"abc". This gives usSeq("abc", "abc", "abc").groupBy(identity)groups the strings by themselves, resulting in exactly theMap[String, Seq[String]]you need:Map("abc" -> Seq("abc", "abc", "abc")).
优化方案2:用collect做显式模式匹配
If you prefer more explicit control (like making it clear you're only handling Some cases), use collect with pattern matching:
val result: Map[String, Seq[String]] = t.collect { case A(Some(s)) => s }.groupBy(identity)
collectonly keeps elements that match the patternA(Some(s)), extracting the stringseach time. Again, this filters out theA(None)entry and gives us the same sequence of strings.- Grouping with
identitythen gives the desired map.
等价性验证
Both approaches produce exactly the same result as your original logic (after converting the grouped A instances to their inner strings). They're safer, more readable, and follow Scala's functional programming best practices by avoiding direct get calls (even if they were safe here).
内容的提问来源于stack exchange,提问作者coder25

