Scala – Pattern Matching to check if string is null or empty

pattern matchingscala

Is it possible to check if string is null or empty using match?

I'm trying to do something like:

def sendToYahoo(message:Email) ={
  val clientConfiguration = new ClientService().getClientConfiguration()
  val messageId : Seq[Char] = message.identifier
  messageId match {
    case messageId.isEmpty => validate()
    case !messageId.isEmpty => //blabla
  }
}

But i have a compile error.

Thank in advance.

Best Answer

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
}
Related Topic