Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala check if string in option is defined and empty

Tags:

scala

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?

like image 703
oym Avatar asked Jun 13 '14 03:06

oym


2 Answers

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
like image 198
Kigyo Avatar answered Oct 08 '22 02:10

Kigyo


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.

like image 39
Dave Griffith Avatar answered Oct 08 '22 02:10

Dave Griffith