scala 如何在scala的单个语句中检查null?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5740906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check for null in a single statement in scala?
提问by theTuxRacer
In my scala code:
在我的 Scala 代码中:
QueueManager.add(getObject)
where getObjectis a method that returns an object of type QueueObject.
wheregetObject是一个返回类型对象的方法QueueObject。
def getObject : QueuObject = {
val response = //some response
return response
}
Is there a way I can check for the response being null, while adding the QueueObject? I know I can do this:
有没有办法可以在添加 QueueObject 时检查响应是否为空?我知道我可以这样做:
if (getObject != null)
QueueManager.add(getObject)
But I do not wish to add a level of indentation. Is there an operator that does that inline?
但我不想添加缩进级别。有没有内联的运算符?
Thanks.
谢谢。
回答by Jesper
Try to avoid using nullin Scala. It's really there only for interoperability with Java. In Scala, use Optionfor things that might be empty. If you're calling a Java API method that might return null, wrap it in an Optionimmediately.
尽量避免null在 Scala 中使用。它实际上只是为了与 Java 的互操作性。在 Scala 中,Option用于可能为空的事物。如果您正在调用可能返回 的 Java API 方法,请立即null将其包装起来Option。
def getObject : Option[QueueObject] = {
// Wrap the Java result in an Option (this will become a Some or a None)
Option(someJavaObject.getResponse)
}
Note: You don't need to put it in a valor use an explicit
returnstatement in Scala; the result will be the value of
the last expression in the block (in fact, since there's only one statement, you don't even need a block).
注意:在 Scala 中,您不需要将其放入 aval或使用显式
return语句;结果将是块中最后一个表达式的值(实际上,因为只有一个语句,您甚至不需要块)。
def getObject : Option[QueueObject] = Option(someJavaObject.getResponse)
Besides what the others have already shown (for example calling foreachon the Option, which might be slightly confusing), you could also call mapon it (and ignore the result of the map operation if you don't need it):
再说一下别人已经显示(例如呼叫foreach上Option,这可能稍微有一些混乱),你也可以调用map它(而忽略了地图操作的结果,如果你不需要它):
getObject map QueueManager.add
This will do nothing if the Optionis a None, and call QueueManager.addif it is a Some.
这将做什么,如果Option是None,并调用QueueManager.add如果它是一个Some。
I find using a regular ifhowever clearer and simpler than using any of these "tricks" just to avoid an indentation level. You could also just write it on one line:
我发现使用常规if但比使用任何这些“技巧”更清晰、更简单,只是为了避免缩进级别。你也可以把它写在一行上:
if (getObject.isDefined) QueueManager.add(getObject.get)
or, if you want to deal with nullinstead of using Option:
或者,如果您想处理null而不是使用Option:
if (getObject != null) QueueManager.add(getObject)
edit- Ben is right, be careful to not call getObjectmore than once if it has side-effects; better write it like this:
编辑- Ben 是对的,getObject如果有副作用,请注意不要多次调用;最好这样写:
val result = getObject
if (result.isDefined) QueueManager.add(result.get)
or:
或者:
val result = getObject
if (result != null) QueueManager.add(result)
回答by Ben Hymanson
If it instead returned Option[QueueObject]you could use a construct like getObject.foreach { QueueManager.add }. You can wrap it right inline with Option(getObject).foreach ...because Option[QueueObject](null)is None.
如果它返回,Option[QueueObject]您可以使用像getObject.foreach { QueueManager.add }. 您可以将其正确内联包装,Option(getObject).foreach ...因为Option[QueueObject](null)is None。
回答by Daniel C. Sobral
Option(getObject) foreach (QueueManager add)
回答by Jean-Philippe Pellet
Although I'm sure @Ben Hymanson's asnwer with Option(getObject).foreachis the preferred way of doing it, I like to use an AnyRefpimp that allows me to write:
虽然我确信@Ben Hymanson 的 asnwer withOption(getObject).foreach是首选方式,但我喜欢使用一个AnyRef皮条客,它允许我写:
getObject ifNotNull ( QueueManager.add(_) )
I find it reads better.
我觉得它读起来更好。
And, in a more general way, I sometimes write
而且,以更一般的方式,我有时会写
val returnVal = getObject ifNotNull { obj =>
returnSomethingFrom(obj)
} otherwise {
returnSomethingElse
}
... replacing ifNotNull with ifSome if I'm dealing with an Option. I find it clearer than first wrapping in an option and then pattern-matching it.
...如果我正在处理一个Option. 我发现它比首先包装在一个选项中然后对其进行模式匹配更清晰。
(For the implementation, see Implementing ifTrue, ifFalse, ifSome, ifNone, etc. in Scala to avoid if(...) and simple pattern matchingand the Otherwise0/Otherwise1classes.)
(有关实现,请参阅在 Scala 中实现 ifTrue、ifFalse、ifSome、ifNone 等以避免 if(...) 和简单模式匹配以及Otherwise0/Otherwise1类。)

