加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 选项GenTraversableOnce?

发布时间:2020-12-16 09:19:00 所属栏目:安全 来源:网络整理
导读:我很困惑.在TraversableLike中,有一个带有签名的flatMap函数 flatMap [B](f:(A)?GenTraversableOnce [B]):可迭代[B] 但是,我可以这样使用它 scala Iterable(1,2,3,4,5).flatMap{i=if (i%2==0) {None} else {Some(i)}}res1: Iterable[Int] = List(1,5) 为什
我很困惑.在TraversableLike中,有一个带有签名的flatMap函数

flatMap [B](f:(A)?GenTraversableOnce [B]):可迭代[B]

但是,我可以这样使用它

scala> Iterable(1,2,3,4,5).flatMap{i=>if (i%2==0) {None} else {Some(i)}}
res1: Iterable[Int] = List(1,5)

为什么有可能选项如何转换为GenTraversableOnce?它似乎不像一个子类…

解决方法

实际上,默认情况下,从Some [X]到GenTraversableOnce [X]的隐式转换.这在REPL中测试非常简单

scala>  implicitly[Function[Some[Int],GenTraversableOnce[Int]]]
res1: Some[Int] => scala.collection.GenTraversableOnce[Int] = <function1>

scala> implicitly[Some[Int] => GenTraversableOnce[Int]] // alternative syntax
res2: Some[Int] => scala.collection.GenTraversableOnce[Int] = <function1>

实际上这是在对象选项中定义的.内部scala包:

object Option {
  /** An implicit conversion that converts an option to an iterable value
   */
  implicit def option2Iterable[A](xo: Option[A]): Iterable[A] = xo.toList

  /** An Option factory which creates Some(x) if the argument is not null,*  and None if it is null.
   *
   *  @param  x the value
   *  @return   Some(value) if value != null,None if value == null
   */
  def apply[A](x: A): Option[A] = if (x == null) None else Some(x)

  /** An Option factory which returns `None` in a manner consistent with
   *  the collections hierarchy.
   */
  def empty[A] : Option[A] = None
}

option2Intable是你正在寻找的.您还可以看到为什么在您的REPL中测试时,您可以看到GenTraversableOnce的实现是一个列表.

如果您正在寻找在您没有做任何事情的情况下自动导入的隐式转换(例如您可以在REPL中使用隐式视图),您必须查看:

> Predef.scala>类的伴随对象

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读