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.
Try to avoid using
null
in Scala. It's really there only for interoperability with Java. In Scala, useOption
for things that might be empty. If you're calling a Java API method that might returnnull
, wrap it in anOption
immediately.Note: You don't need to put it in a
val
or use an explicitreturn
statement 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).Besides what the others have already shown (for example calling
foreach
on theOption
, which might be slightly confusing), you could also callmap
on it (and ignore the result of the map operation if you don't need it):This will do nothing if the
Option
is aNone
, and callQueueManager.add
if it is aSome
.I find using a regular
if
however clearer and simpler than using any of these "tricks" just to avoid an indentation level. You could also just write it on one line:or, if you want to deal with
null
instead of usingOption
:edit - Ben is right, be careful to not call
getObject
more than once if it has side-effects; better write it like this:or:
If it instead returned
Option[QueueObject]
you could use a construct likegetObject.foreach { QueueManager.add }
. You can wrap it right inline withOption(getObject).foreach ...
becauseOption[QueueObject](null)
isNone
.Although I'm sure @Ben Jackson's asnwer with
Option(getObject).foreach
is the preferred way of doing it, I like to use anAnyRef
pimp that allows me to write:I find it reads better.
And, in a more general way, I sometimes write
... 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.)