模式匹配以检查字符串是否为空或空

pla*_*oom 14 scala pattern-matching

是否可以使用匹配检查字符串是空还是空?

我正在尝试做类似的事情:

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
  }
}
Run Code Online (Sandbox Code Playgroud)

但我有一个编译错误.

预先感谢.

Gab*_*lla 31

你可以写一个简单的函数,如:

def isEmpty(x: String) = Option(x).forall(_.isEmpty)
Run Code Online (Sandbox Code Playgroud)

要么

def isEmpty(x: String) = x == null || x.isEmpty
Run Code Online (Sandbox Code Playgroud)

如果您认为" "是空的,您可能还想修剪字符串.

def isEmpty(x: String) = x == null || x.trim.isEmpty
Run Code Online (Sandbox Code Playgroud)

然后使用它

val messageId = message.identifier
messageId match {
  case id if isEmpty(id) => validate()
  case id => // blabla
}
Run Code Online (Sandbox Code Playgroud)

或没有 match

if (isEmpty(messageId)) {
  validate()
} else {
  // blabla
}
Run Code Online (Sandbox Code Playgroud)

甚至

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
}
Run Code Online (Sandbox Code Playgroud)


Lee*_*Lee 8

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