Check if a string is blank or doesn't exist in Scala

Soumya Simanta picture Soumya Simanta · Jun 6, 2014 · Viewed 53.9k times · Source

I have an Option[String].

I want to check if there is a string exists and if it's exists its not blank.

def isBlank( input : Option[String]) : Boolean = 
{ 
     input.isEmpty || 
     input.filter(_.trim.length > 0).isEmpty 
}

Is there is a better way of doing this in Scala ?

Answer

wheaties picture wheaties · Jun 6, 2014

What you should do is check using exists. Like so:

myOption.exists(_.trim.nonEmpty)

which will return True if and only if the Option[String] is not None and not empty.