请说明发生了什么以及为什么会导致Set(1)。
val myMap = Map("a" -> 1, "b" -> 2, "c" -> 3)
Set("a", "d") collect myMap
res0:scala.collection.immutable.Set [Int] = Set(1)
Scala documentation Set说, collect 方法采用PartialFunction。那怎么用Map来产生结果呢?
def collect[B](pf: PartialFunction[A, B]): Set[B] [use case] Builds a new collection by applying a partial function to all elements of this immutable set on which the function is defined.
如果collect使用PartialFunction,它应该如下所示吗?
val mySet = Set("a", "d")
val first = mySet.collect(new PartialFunction[String, String]{
def apply(i: String) = i
def isDefinedAt(i: String) = ! i.isEmpty()
})
first.foreach((println(_)))
如果是这样,请通过PartialFunction方式提供“ Set(“ a”,“ d”)收集myMap”的实现。