How to check for null or false in Scala concisely?

后端 未结 7 1558
时光取名叫无心
时光取名叫无心 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:47

    Using pattern matching as suggested in a couple of answers here is a nice approach:

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

    But, a bit verbose.

    I prefer to map an Option in the following way:

    Option(getSomething()) map (something -> doSomethingWith(something))

    One liner, short, clear.

    The reason to that is Option can be viewed as some kind of collection – some special snowflake of a collection that contains either zero elements or exactly one element of a type and as as you can map a List[A] to a List[B], you can map an Option[A] to an Option[B]. This means that if your instance of Option[A] is defined, i.e. it is Some[A], the result is Some[B], otherwise it is None. It's really powerful!

提交回复
热议问题