8

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?

3 Answers 3

11

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
Sign up to request clarification or add additional context in comments.

1 Comment

This actually does logically what I need - I needed it to return true in the case of None..my fault since I clarified the question after @Dave's answers
5
myOption.forall(_.isEmpty)

The general rule is that for pretty much anything you would want to do with an Option, there's a single method that does it.

6 Comments

This will yield false, when myOption is None. myOption.getOrElse("").isEmpty would yield true.
cool. could you please explain the "_.isEmpty" portion? I see from the type definition that exists takes an a predicate (a function returning a boolean) but I have not encountered the shorthand with the underscore.
@oym its syntactic sugar for myOption.exists(x => x.isEmpty)
@Kigyo I see. So the underscore is somehow a reference to the outer value?
exists expects a function String => Boolean (in this case). The underscore represents the input string parameter.
|
0

You can do same using below

def foo(s: Option[String]) = s.exists(_.trim.nonEmpty)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.