How to check for null or false in Scala concisely?

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

    Well, Boolean cannot be null, unless passed as a type parameter. The way to handle null is to convert it into an Option, and then use all the Option stuff. For example:

    Option(some) foreach { s => println(s) }
    Option(some) getOrElse defaultValue
    

    Since Scala is statically type, a thing can't be "a null or is empty string or is zero number etc". You might pass an Any which can be any of those things, but then you'd have to match on each type to be able to do anything useful with it anyway. If you find yourself in this situation, you most likely are not doing idiomatic Scala.

提交回复
热议问题