Alex Rivera | Logout

How to check for null in a single statement in scala?

Asked 2011-04-21T07:26:56.900
66

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.

Edit
Report

1 Answer

6

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.)

answered 2011-04-21T08:21:22.943

Your Answer