How to check for null or false in Scala concisely?

后端 未结 7 1573
时光取名叫无心
时光取名叫无心 2020-12-24 06:23

In Groovy language, it is very simple to check for null or false like:

groovy code:

def some = getSomething()
if(some) {
//         


        
7条回答
  •  渐次进展
    2020-12-24 06:48

    What you may be missing is that a function like getSomething in Scala probably wouldn't return null, empty string or zero number. A function that might return a meaningful value or might not would have as its return an Option - it would return Some(meaningfulvalue) or None.

    You can then check for this and handle the meaningful value with something like

     val some = getSomething()
     some match {
        case Some(theValue) => doSomethingWith(theValue)
        case None           => println("Whoops, didn't get anything useful back")
     }
    

    So instead of trying to encode the "failure" value in the return value, Scala has specific support for the common "return something meaningful or indicate failure" case.

    Having said that, Scala's interoperable with Java, and Java returns nulls from functions all the time. If getSomething is a Java function that returns null, there's a factory object that will make Some or None out of the returned value.

    So

      val some = Option(getSomething())
      some match {
        case Some(theValue) => doSomethingWith(theValue)
        case None           => println("Whoops, didn't get anything useful back")
      }
    

    ... which is pretty simple, I claim, and won't go NPE on you.

    The other answers are doing interesting and idiomatic things, but that may be more than you need right now.

提交回复
热议问题