user866364
user866364

Reputation:

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.

Upvotes: 27

Views: 73446

Answers (3)

Kamau
Kamau

Reputation: 23

If you're looking to check whether a String is null or empty, here's a one-liner that does that. You wrap it with an Option, use filter to make sure it's not an empty String then call getOrElse to provide a default value in case the original value is either null or an empty String.

Option(s).filter(!_.isEmpty).getOrElse(columnName)

Upvotes: 1

Gabriele Petronella
Gabriele Petronella

Reputation: 108101

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
}

Upvotes: 56

Lee
Lee

Reputation: 144126

def isNullOrEmpty[T](s: Seq[T]) = s match {
     case null => true
     case Seq() => true
     case _ => false
}

Upvotes: 13

Related Questions