placplacboom placplacboom - 1 month ago 6
Scala Question

Pattern Matching to check if string is null or empty

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.

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
}