Scala check if string is defined in option and empty

Given the following:

myOption: Option[String]

What is the most idiomatic way to check if a String value inside a parameter is empty (if it is not defined, then it should be considered empty)?

Is the myOption.getOrElse("").isEmptybest / cleanest way?

+4
source share
2 answers

You can do

def foo(s: Option[String]) = s.forall(_.isEmpty)

or

def foo(s: Option[String]) = s.fold(true)(_.isEmpty)

foldhas 2 parameters in different lists. The first is for the case None, and the other is evaluated, if any String.

Personally, I would prefer the first solution, but in the second one it is very clear what you want to return truein the case None.

Some examples:

foo(Some(""))   //true
foo(Some("aa")) //false
foo(None)       //true
+7
source
myOption.forall(_.isEmpty)

, , , , .

+4

Source: https://habr.com/ru/post/1544420/


All Articles