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

斯卡拉:隐含的扁平化?

发布时间:2020-12-16 18:12:12 所属栏目:安全 来源:网络整理
导读:Welcome to Scala version 2.10.1 (OpenJDK 64-Bit Server VM,Java 1.6.0_27).Type in expressions to have them evaluated.Type :help for more information.scala def o1: Option[Option[Unit]] = Some(()).map(Some(_))o1: Option[Option[Unit]]scala o1r
Welcome to Scala version 2.10.1 (OpenJDK 64-Bit Server VM,Java 1.6.0_27).
Type in expressions to have them evaluated.
Type :help for more information.

scala> def o1: Option[Option[Unit]] = Some(()).map(Some(_))
o1: Option[Option[Unit]]

scala> o1
res0: Option[Option[Unit]] = Some(Some(()))

到目前为止一切都如预期.但是如果我们忘记指定我们在Option中嵌套了一个Option呢?

scala> def o2: Option[Unit] = Some(()).map(Some(_))
o2: Option[Unit]

scala> o2
res1: Option[Unit] = Some(())

为什么编译器会接受这个并隐含地将值展平?

解决方法

任何东西都可以转换成单位:

scala> val a: Unit = Some(())
a: Unit = ()

对于你的o2,编译器将Some [Unit]转换为Unit.请注意,当然,如果您将Int替换为Unit,则不会发生这种情况,例如:

scala> def o2: Option[Int] = Some(4).map(Some(_))
<console>:7: error: type mismatch;
 found   : Some[Int]
 required: Int
       def o2: Option[Int] = Some(4).map(Some(_))

(编辑:李大同)

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

    推荐文章
      热点阅读