placplacboom placplacboom - 1 year ago 95
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 Source

You can write a simple function like:

def isEmpty(x: String) = Option(x).forall(_.isEmpty)


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)) {
} else {
  // blabla
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download