【发布时间】:2018-06-12 15:01:25
【问题描述】:
我正在尝试理解并编写了以下代码:
object Main extends App {
val resultOption: Option[Int] =
for{
i1 <- opt1
i2 <- opt2
} yield {
if(i1 + i2 > 10) null.asInstanceOf[Int]
else i1 + i2
}
println(resultOption) // <---- Here
def opt1: Option[Int] = //some computations
def opt2: Option[Int] = //some computations
}
我希望 resultOption 成为 None 以防满足条件,但返回了 Some(0)。我查看了 yield 块的编译代码,我们这里有:
Code:
0: aload_0
1: getfield #25 // Field i1$1:I
4: iload_1
5: iadd
6: bipush 10
8: if_icmple 18
11: aconst_null
12: invokestatic #31 // Method scala/runtime/BoxesRunTime.unboxToInt:(Ljava/lang/Object;)I
15: goto 24
18: aload_0
19: getfield #25 // Field i1$1:I
22: iload_1
23: iadd
24: ireturn
在12:,我们调用BoxesRunTime.unboxToInt(null),它确实返回0。问题是在i1 + i2 > 10 的情况下如何产生None。
【问题讨论】:
标签: scala for-comprehension scala-option