narthi
narthi

Reputation: 2228

Scala: implicit flattening?

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

So far all is as expected. But what if we forget to specify that we have an Option nested in an Option?

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

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

Why does the compiler accept this and implicitly flatten the value?

Upvotes: 4

Views: 342

Answers (1)

Jean-Philippe Pellet
Jean-Philippe Pellet

Reputation: 60006

Anything can be converted to Unit:

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

For your o2, the compiler converts Some[Unit] to Unit. Note that, of course, it doesn't happen if you replace Unit by Int, for instance:

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(_))

Upvotes: 6

Related Questions