oym oym - 8 months ago 58
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)?

the best / cleanest way?


You can do

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


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