【发布时间】:2017-09-19 08:26:31
【问题描述】:
如果编译器在这种情况下不推断包装,我不明白在 scala 中使用可选类型的意义:
f(null) // WHY ISN"T THE COMPILER DOING ANYTHING HERE!
def f(x : Option[String]) = {
// WHY DOES IT CRASH WHEN MATCHING "SOME(NULL)" !!
val = x match {
case Some(x) => s"blah blah append $x"
case None => "" // !!! BOOM CRASH null scala.MatchError: null
at
}
...
...
}
如果我现在仍需要在 f 函数中检查 null,我会得到什么???
def f(x : Option[String]) = {
// DON'T CRASH ?????
if (x != null) {
// now I can pattern match??? what is the point of the option???
e match {... , case None => ??? what was the point of this?
} else {
e match { ...// BOOM ! CRASH AND BURN because "some" is NULL??? }
}
}
【问题讨论】:
-
Option是一种简单的数据类型,而不是编译器魔法。好的做法(大多数 Scala 库都遵循)是用None表示缺失的东西,如果无法避免,则仅将null用于 Java 互操作
标签: scala syntax pattern-matching optional