设置我有类Set[String]
类型的字段。另外,我有这个类的对象列表。我想将所有这些对象集合中的所有字符串收集到一个集合中。这是我如何能做到这一点已经:斯卡拉:使用列表中flatMap
case class MyClass(field: Set[String])
val list = List(
MyClass(Set("123")),
MyClass(Set("456", "798")),
MyClass(Set("123", "798"))
)
list.flatMap(_.field).toSet // Set(123, 456, 798)
它的工作原理,但我想,我可以只使用flatMap
达到同样的,没有toSet
调用。我想这一点,但它给了编译错误:
// error: Cannot construct a collection of type Set[String]
// with elements of type String based on a collection of type List[MyClass].
list.flatMap[String, Set[String]](_.field)
如果我改变的list
到Set
类型(即val list = Set(...)
),那么这样的flatMap
调用工作。
所以,我可以用某种方式Set.canBuildFrom
或任何其他CanBuildFrom
对象调用flatMap
上List
对象,这样我会得到Set
结果?
因为'foldLeft'接受函数,所以在这里不需要使用'case'两个参数,即'(_ ++ _.field)' –
你当然是正确的@Oneg,但为了清晰起见,我明确表示。 – mdm
您仍然可以省略“case”关键字,因为您没有进行任何重要的模式匹配 –