如何在 Scala 中简洁地检查 null 或 false? [英] How to check for null or false in Scala concisely?
问题描述
在 Groovy 语言中,检查 null
或 false
非常简单,例如:
In Groovy language, it is very simple to check for null
or false
like:
常规代码:
def some = getSomething()
if(some) {
// do something with some as it is not null or emtpy
}
在 Groovy 中,如果 some
为 null
或为空字符串或为零数字等,则计算结果为 false
.在 Scala 中测试 null
或 false
的类似简洁方法是什么?假设 some
只是 Java 类型的 String,这部分问题的简单答案是什么?
In Groovy if some
is null
or is empty string or is zero number etc. will evaluate to false
. What is similar concise method of testing for null
or false
in Scala?
What is the simple answer to this part of the question assuming some
is simply of Java type String?
在 groovy 中还有一个更好的方法是:
Also another even better method in groovy is:
def str = some?.toString()
这意味着如果 some
不是 null
那么 some
上的 toString
方法将被调用而不是抛出NPE 以防 some
为 null
.Scala 中有哪些相似之处?
which means if some
is not null
then the toString
method on some
would be invoked instead of throwing NPE in case some
was null
. What is similar in Scala?
推荐答案
您可能遗漏的是 Scala 中的 getSomething
之类的函数可能不会返回 null、空字符串或零数.一个函数可能会返回一个有意义的值,也可能不会返回一个 Option
- 它会返回 Some(meaningfulvalue)
或 None
.
What you may be missing is that a function like getSomething
in Scala probably wouldn't return null, empty string or zero number. A function that might return a meaningful value or might not would have as its return an Option
- it would return Some(meaningfulvalue)
or None
.
然后你可以检查这个并用类似的东西处理有意义的值
You can then check for this and handle the meaningful value with something like
val some = getSomething()
some match {
case Some(theValue) => doSomethingWith(theValue)
case None => println("Whoops, didn't get anything useful back")
}
因此,Scala 没有尝试在返回值中编码失败"值,而是特别支持常见的返回有意义的东西或指示失败"的情况.
So instead of trying to encode the "failure" value in the return value, Scala has specific support for the common "return something meaningful or indicate failure" case.
话虽如此,Scala 可与 Java 互操作,而且 Java 始终从函数中返回空值.如果 getSomething
是一个返回 null 的 Java 函数,则有一个工厂对象可以从返回值中生成 Some 或 None .
Having said that, Scala's interoperable with Java, and Java returns nulls from functions all the time. If getSomething
is a Java function that returns null, there's a factory object that will make Some or None out of the returned value.
所以
val some = Option(getSomething())
some match {
case Some(theValue) => doSomethingWith(theValue)
case None => println("Whoops, didn't get anything useful back")
}
...这很简单,我声称,并且不会对您进行 NPE.
... which is pretty simple, I claim, and won't go NPE on you.
其他答案正在做有趣和惯用的事情,但这可能比您现在需要的更多.
The other answers are doing interesting and idiomatic things, but that may be more than you need right now.
这篇关于如何在 Scala 中简洁地检查 null 或 false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!