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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27941585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 06:49:41  来源:igfitidea点击:

Pattern Matching to check if string is null or empty

scalapattern-matching

提问by placplacboom

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.

预先感谢。

回答by Gabriele Petronella

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

或没有 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
}

回答by Lee

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

回答by Kamau

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.

如果您想检查 String 是 null 还是空,这里有一个单行程序可以做到这一点。你用一个选项包装它,使用过滤器来确保它不是一个空字符串,然后调用 getOrElse 来提供一个默认值,以防原始值为空或空字符串。

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