In my scala code:
QueueManager.add(getObject)
where getObject
is a method that returns an object of type 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:
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.
Option(getObject) foreach (QueueManager add)
Although I'm sure @Ben Jackson's asnwer with Option(getObject).foreach
is the preferred way of doing it, I like to use an AnyRef
pimp that allows me to write:
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.
(For the implementation, see Implementing ifTrue, ifFalse, ifSome, ifNone, etc. in Scala to avoid if(...) and simple pattern matching and the Otherwise0
/Otherwise1
classes.)
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
.
Source: Stackoverflow.com