oym
oym

Reputation: 7083

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?

Upvotes: 8

Views: 13851

Answers (3)

Pankaj Patil
Pankaj Patil

Reputation: 96

You can do same using below

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

Upvotes: 0

Dave Griffith
Dave Griffith

Reputation: 20515

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.

Upvotes: 5

Kigyo
Kigyo

Reputation: 5768

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

Upvotes: 11

Related Questions