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(())
为什么编译器接受这个并隐式地压平该值?
最佳答案
任何东西都可以转换为 Unit
:
scala> val a: Unit = Some(())
a: Unit = ()
为您
o2
, 编译器转换 Some[Unit]
至 Unit
.请注意,当然,如果替换 Unit
则不会发生这种情况。来自 Int
, 例如: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(_))
关于Scala:隐式展平?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18241095/