什么是list productiterator scala的用法

时间:2016-12-13 14:27:25

标签: scala

scala中List类的productiterator方法的用例是什么

Apple      1
Banana     1
Orange     1
Apple      2
Plum       1
Orange     2
Apple      3

2 个答案:

答案 0 :(得分:3)

List的productIterator没有特定用例。列表是Product因此它实现了Product trait,我没有看到productIterator的任何好用例。您当然更愿意使用list.headlist.headOptionlist.tail。如果您想迭代List,则可以在不使用productIterator的情况下进行迭代。

或者,如果您正在进行模式匹配,则可以使用:h :: t

如果您想迭代productIteratorTuple的所有元素,

case class函数更有意义,因为所有case classes都会综合实现Product生成的方法。

答案 1 :(得分:1)

我认为确实没有用例。

严格来说,缺点列表是arity 2或arity 0的Product。曾几何时,在类型中反映它似乎也是一个好主意。 ::是一个案例类(无论如何总是继承Product),原因很多,因此NilListProduct也有意义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; } 并没有用。有更好的,更惯用的替代品。