Scala: implicit smoothing?

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, everything is as expected. But what if we forget to indicate that we have an Option nested in 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 align the value?

+4
source share
1 answer

All that can be converted to Unit :

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

For your o2 compiler will convert Some[Unit] to Unit . Note that of course this does not happen if you replace Unit with Int , for example:

 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(_)) 
+6
source

Source: https://habr.com/ru/post/1497112/


All Articles