Option.zip 返回列表,而不是选项 [英] Option.zip returns List, not Option

查看:33
本文介绍了Option.zip 返回列表,而不是选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标准库文档将 zip 部分签名描述为 def zip[B](that: GenIterable[B]): Option[(A, B)]Some(1) zip Some(2) 返回一个 List((1,2)) 而不是 Some((1,2)).是错误的实现还是错误的文档?

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?

推荐答案

有问题的文档.

zip实际上是定义在Iterable上的,由于隐式转换option2Iterable,所以适用于Option(如果您仔细观察,这在文档中已明确说明).

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).

为此,Option 首先转换为 Iterable,然后支持 zip 操作.

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

这是为了代码重用而完成的,但它忽略了一些情况,其中 Iterable 方法直接在 Option 上有意义,而无需隐式转换.

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.

这是邮件列表中的相关讨论:https://groups.google.com/forum/#!topic/scala-language/MFU5PPt_jYw

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

如果您确实需要 zip 两个选项,您可以使用此解决方法:

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

(opt1 zip opt2).headOption

此外,正如 Travis 在评论中指出的那样,您也可以利用 scalaz Zip 类型类,尽管您必须改用 fzip.

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

这篇关于Option.zip 返回列表,而不是选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆