【问题标题】:what is use of list productiterator scalalist productiterator scala有什么用
【发布时间】:2016-12-13 14:27:25
【问题描述】:

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

val l1 = List(1.1, 2.2, 3.3)
val it = l1.productIterator
//I get the following result
res0: Double = 1.1
res1: List[Double] = List(2.2, 3.3)

//but I can get the same using head and tail

l1.head
1.1

l1.tail
List(2.2, 3.3)

【问题讨论】:

标签: scala


【解决方案1】:

List 的 productIterator 没有特定的用例。列表是Product,因此它实现了Product trait,我看不到productIterator 的任何好的用例。您当然更喜欢使用list.headlist.headOptionlist.tail。如果您想遍历List,您已经可以在不使用productIterator 的情况下执行此操作。

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

如果您想遍历Tuplecase class 的所有元素,productIterator 函数更有意义,因为所有case classes 都使用综合生成的方法实现Product

【讨论】:

    【解决方案2】:

    我认为没有真正的用例。

    严格来说,cons 列表是 arity 2 或 arity 0 的 Product。曾几何时,在其类型中也反映这一点似乎是个好主意。并且:: 是一个案例类(无论如何它总是继承Product),原因有很多,所以NilList 也可以成为Product

    但是Product 提供的方法对于List 来说并没有真正的用处。还有更好、更惯用的替代方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-23
      • 2012-01-02
      • 2020-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-03
      • 1970-01-01
      相关资源
      最近更新 更多