In Groovy language, it is very simple to check for null or false like:
groovy code:
def some = getSomething()
if(some) {
// do something with some as it is not null or emtpy
}
In Groovy if some is null or is empty string or is zero number etc. will evaluate to false. What is similar concise method of testing for null or false in Scala?
What is the simple answer to this part of the question assuming some is simply of Java type String?
Also another even better method in groovy is:
def str = some?.toString()
which means if some is not null then the toString method on some would be invoked instead of throwing NPE in case some was null. What is similar in Scala?
What you may be missing is that a function like
getSomethingin 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 anOption– it would returnSome(meaningfulvalue)orNone.You can then check for this and handle the meaningful value with something like
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
getSomethingis a Java function that returns null, there’s a factory object that will make Some or None out of the returned value.So
… 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.