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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With