Scala的支持一样的Java null
。所以你的代码是合理正确的。
但是,更现代的方法是确保您的代码几乎永远不会触及null
值。为了做到这一点,一种可能的方式是使用Scala Option
类。 Option[T]
是一个值,可以或不可以定义。已定义的选项由Some[T]
表示,而未定义的选项由None
表示。
Option(thirdpartyCall.collectValue())
将返回Option[Double]
。有多种方法来检查包含在Option
的价值,斯卡拉,惯用的方式之一来执行你想要做的是pattern matching:
Option(thirdpartyCall.collectValue()) match {
case Some(value) =>
println(s"value is defined: $value")
case None =>
println("value is not defined")
}
然而,Option
比更强大。它支持像map
,flatMap
和fold
,让你可以更加表现方法,例如:
def optionIsDefined[A](a: A) = Option(a).fold("not defined") { value => s"defined with value: $value" }
scala> optionIsDefined(42)
res2: String = defined with value: 42
scala> optionIsDefined(null)
res3: String = not defined
This是一个伟大的新来者对Option
友好的向导。