Manu Chadha
Manu Chadha

Reputation: 16723

what is use of list productiterator scala

what is the usecase of productiterator method in List class in scala

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)

Upvotes: 2

Views: 2432

Answers (2)

Jasper-M
Jasper-M

Reputation: 15086

I don't think there really is a use case.

Strictly speaking a cons list is a Product of either arity 2 or arity 0. Once upon a time it must have seemed a good idea to also reflect that in its type. And :: is a case class (which always inherits Product anyway) for many good reasons, so it makes some sense for Nil and List to then also be a Product.

But the methods that Product gives you are not really useful for a List. There are better, more idiomatic, alternatives.

Upvotes: 1

Nikola Stojiljkovic
Nikola Stojiljkovic

Reputation: 693

There is no specific use case for List's productIterator. List is the Product therefore it implements the Product trait and I don't see any good use case of productIterator. You would certainly prefer to use list.head, list.headOption or list.tail. If you wanted to iterate over the List, you can already do that without using the productIterator.

Or if you were doing the pattern matching you could use: h :: t.

productIterator function makes more sense if you wanted to iterate over all elements of the Tuple or maybe case class, since all case classes implement Product with synthetically generated methods.

Upvotes: 3

Related Questions