scala中List类的productiterator方法的用例是什么
Apple 1
Banana 1
Orange 1
Apple 2
Plum 1
Orange 2
Apple 3
答案 0 :(得分:3)
List的productIterator没有特定用例。列表是Product
因此它实现了Product trait
,我没有看到productIterator
的任何好用例。您当然更愿意使用list.head
,list.headOption
或list.tail
。如果您想迭代List
,则可以在不使用productIterator
的情况下进行迭代。
或者,如果您正在进行模式匹配,则可以使用:h :: t
。
productIterator
或Tuple
的所有元素, case class
函数更有意义,因为所有case classes
都会综合实现Product
生成的方法。
答案 1 :(得分:1)
我认为确实没有用例。
严格来说,缺点列表是arity 2或arity 0的Product
。曾几何时,在类型中反映它似乎也是一个好主意。 ::
是一个案例类(无论如何总是继承Product
),原因很多,因此Nil
和List
对Product
也有意义Product
1}}。
但是List
给你的方法对class DefaultMap extends Map {
constructor(defaultConstructor) {
super();
this.defaultConstructor = defaultConstructor;
}
get(key) {
if (this.has(key)) {
return super.get(key);
}
const def = this.defaultConstructor();
this.set(key, def);
return def;
}
}
function groupBy(collection, key) {
const groups = new DefaultMap(() => []);
for (const item of collection) {
const itemKey = key(item);
const group = groups.get(itemKey);
group.push(item);
}
return groups;
}
并没有用。有更好的,更惯用的替代品。