【发布时间】:2011-10-18 23:23:19
【问题描述】:
当我写我的recent answer 时,我也尝试以更“实用”的方式解决问题,但遇到了以下问题:
scala> "1".asInstanceOf[Int]
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
at scala.runtime.BoxesRunTime.unboxToInt(Unknown Source)
...
但
scala> Some("1".asInstanceOf[Int])
res29: Some[Int] = Some(1)
并且只有
scala> res29.get
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
at scala.runtime.BoxesRunTime.unboxToInt(Unknown Source)
...
看起来 Some 的论点是惰性求值的,但我在 the sources 中找不到任何线索。 Some 构造函数中的 x 参数是严格的。
为什么 Some 和 asInstanceOf 会出现这种奇怪的行为?
【问题讨论】:
-
您使用的是哪个 scala 版本? 2.9.0.1 中的 REPL 在这两种情况下都会立即抛出异常。
-
我复制了它,但在 2.8.1 上。很高兴知道它已修复。
-
Scala 2.8.1,我实际上在生产中使用了这个版本。很高兴知道是什么导致了这种行为以及它会在哪些情况下出现。
标签: scala option lazy-evaluation