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

前端 未结 4 1010
轻奢々
轻奢々 2020-12-23 09:28

In my scala code:

QueueManager.add(getObject)

where getObject is a method that returns an object of type QueueObject

4条回答
  •  别那么骄傲
    2020-12-23 10:07

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

提交回复
热议问题