oym oym - 3 months ago 16
Scala Question

Scala check if string in option is defined and empty

Given the following:

myOption: Option[String]


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

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

Answer

You can do

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

Or

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

fold has 2 parameters in different lists. The first one is for the None case and the other gets evaluated if there is some String.

Personally I would prefer the first solution, but the second one makes it very clear that you want to return true in case of None.

Some examples:

foo(Some(""))   //true
foo(Some("aa")) //false
foo(None)       //true