Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Option.zip returns List, not Option

Tags:

scala

Standard library documentation describes zip partial signature as def zip[B](that: GenIterable[B]): Option[(A, B)] but Some(1) zip Some(2) returns a List((1,2)) not Some((1,2)). Is it a case of buggy implementation or buggy documentation?

like image 798
synapse Avatar asked Oct 13 '14 17:10

synapse


1 Answers

Buggy documentation.

zip is actually defined on Iterable, and it's applicable to Option due to the implicit conversion option2Iterable (this is explicitly stated in the documentation if you look closely).

For this reason Option is first converted to an Iterable and then the zip operation is supported.

This is done for code reuse, but it misses some case in which Iterable methods make sense directly on Option without need of an implicit conversion.

Here's a relevant discussion in mailing list: https://groups.google.com/forum/#!topic/scala-language/MFU5PPt_jYw

If you actually need to zip two options, you can use this workaround:

(opt1 zip opt2).headOption

Also, as Travis noted in the comments, you could alternatively leverage scalaz Zip type class, although you would have to use fzip instead.

opt1 fzip opt2
like image 169
Gabriele Petronella Avatar answered Oct 18 '22 22:10

Gabriele Petronella