Scala 趣题 5 The missing list

回忆下Scala的集合框架, 可能有助于理解下面的题目

wKiom1SekKmQfyhDAAIr2mqqkCM825.jpg


两个sum的结果一样吗?

def sumSizes(collections: Iterable[TraversableOnce[_]]): Int = collections.map(_.size).sum

sumSizes(List(Set(1, 2), List(3, 4)))
sumSizes(Set(List(1, 2), Set(3, 4)))


























Explanation

Even though collections.map would appear to map an iterable to another "nice" iterable, since the Collections Redesign the type of the returned iterable will (usually) match the input type. Which, for sets, means...no duplicates. And yes, foldLeft would obviously be a much nicer way to do this :)

map函数的返回类型由调用者的类型决定, Set(2, 2)是不合法的Set,会被转换成Set(2)


你可能感兴趣的:(scala)