gpt4 book ai didi

scala - 为什么 Scala Option.tapEach 返回 Iterable,而不是 Option?

转载 作者:行者123 更新时间:2023-12-03 21:41:54 24 4
gpt4 key购买 nike

scaladocOption.tapEach声明“返回:与此相同的逻辑集合”,正如对以 tap 命名的操作所预期的那样& foreach .但是,它不会返回 Option但是一个 IterableList 支持:

scala> import scala.util.chaining._

scala> Option(5).tap(_.foreach(_ => ()))
val res0: Option[Int] = Some(5)

scala> Option(5).tapEach(_ => ())
val res1: Iterable[Int] = List(5)
(已针对 Scala 2.13.5 和 3.0.0-RC1 进行验证)
有没有好的退货理由 Iterable而不是 Option ,或者这只是被忽视了(最终可能会被修复)?

最佳答案

看来是否Option正如 Make Option extend IterableOnce #8038 中的讨论所指出的,被认为是一个完整的集合有点像蠕虫。 .我觉得相关comment

So it can definitely be a IterableOnce because you can get an iteratorof zero to one elements. But it can't be a Iterable because you youcan't implement fromSpecific(c: IterableOnce[A]): K without throwingaway data.


然而 tapEach 用途 fromSpecific在其定义中
override def tapEach[U](f: A => U): C = fromSpecific(new View.Map(this, { (a: A) => f(a); a })
所以要记住的关键是 Option因为 Scala 2.13 是 IterableOnce但不是完整的 Iterable . IterableOnceIterable 相比更小,因此如果需要来自 Iterable 的功能它是通过隐式转换提供的,按照 docs

This member is added by an implicit conversion from Option[A]to Iterable[A] performed by method option2Iterable in scala.Option.


那是
option2iterable(Option(5)).tapEach(_ => ())
因此 Iterable[Int]返回类型。
还要考虑以下 note

Many of the methods in here are duplicative with those in theTraversable hierarchy, but they are duplicated for a reason: theimplicit conversion tends to leave one with an Iterable in situationswhere one could have retained an Option.


所以贡献者必须在 Option 中烘焙一个专门的版本来保留类型,或者我们可以提供我们自己专门的扩展实现,比如
scala> implicit class OptionTapOps[A](v: Option[A]) {
| def tapEach[B](f: A => B): Option[A] = { v.foreach(f); v }
| }
class OptionTapOps

scala> Option(5).tapEach(_ => ())
val res11: Option[Int] = Some(5)

关于scala - 为什么 Scala Option.tapEach 返回 Iterable,而不是 Option?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67017901/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com