2013-08-14 3 views
4
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(()) 

왜 컴파일러는이를 받아들이고 값을 암시 적으로 평평하게합니까?

답변

6

뭐든지 Unit로 변환 할 수 있습니다 :

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

당신의 o2의 경우, 컴파일러는 UnitSome[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(_)) 
+0

감사합니다 : 당신은 예를 들어, Int에 의해 Unit를 교체 할 경우 그 주, 물론,이 발생하지 않습니다. 스칼라 언어 사양의 관련 섹션을 찾는 사람은 6.26.1입니다 (Value Discarding 참조). –

관련 문제