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[Strin
I added a Scalafiddle to play with that: Scalafiddle
That shows the marked correct answer is wrong (as pointed out by prayagupd):
def isBlank(str: Option[String]): Boolean =
str.forall(_.trim.isEmpty)
the solution is for non-blank:
def isNotBlank(str: Option[String]): Boolean =
str.exists(_.trim.nonEmpty)
You can also take advantage of Extractor pattern. It makes codes much more declarative.
For example:
object NonBlank {
def unapply(s: String): Option[String] = Option(s).filter(_.trim.nonEmpty)
}
And then use it like
def createUser(name: String): Either[Error, User] = name match {
case NonBlank(username) => Right(userService.create(username))
case _ => Left(new Error("Invalid username. Blank usernames are not allowed."))
}
you can also check using lastOption
or headOption
if the string is empty it will return None
scala> "hello".lastOption
res39: Option[Char] = Some(o)
scala> "".lastOption
res40: Option[Char] = None