Pattern Matching to check if string is null or empty
def isNullOrEmpty[T](s: Seq[T]) = s match {
case null => true
case Seq() => true
case _ => false
}
You can write a simple function like:
def isEmpty(x: String) = Option(x).forall(_.isEmpty)
or
def isEmpty(x: String) = x == null || x.isEmpty
You might also want to trim the string, if you consider " "
to be empty as well.
def isEmpty(x: String) = x == null || x.trim.isEmpty
and then use it
val messageId = message.identifier
messageId match {
case id if isEmpty(id) => validate()
case id => // blabla
}
or without a match
if (isEmpty(messageId)) {
validate()
} else {
// blabla
}
or even
object EmptyString {
def unapply(s: String): Option[String] =
if (s == null || s.trim.isEmpty) Some(s) else None
}
message.identifier match {
case EmptyString(s) => validate()
case _ => // blabla
}