hap*_*yes 2 scala pattern-matching
我是 Scala 的新手。我正在编写一个模式匹配如下:
val capitals = Map("France" -> "Paris", "Japan" -> "Tokyo")
show(capitals.get("test"))
def show(x: Option[String]) = x match {
case Some(s) | None => s
}
Run Code Online (Sandbox Code Playgroud)
我收到错误:
Error: illegal variable in pattern alternative
case Some(s) | None => s
^
Run Code Online (Sandbox Code Playgroud)
我想看看我怎样才能达到或达到我在 java 中的 if 语句中的条件
if (str == null || str.isEmpty())
你能帮忙改写代码或指出错误吗?
问题:如何在案例模式匹配中提及或设置条件?
这是您对选项进行模式匹配的方式:
def show(x: Option[String]) = x match {
case Some(s) => s
case None => "N/A"
}
Run Code Online (Sandbox Code Playgroud)
(顺便说一句,你也可以做这样的事情):
capitals.get("test").getOrElse("N/A")
Run Code Online (Sandbox Code Playgroud)
现在,要将 OR 条件添加到模式匹配案例中,您不能使用绑定变量。但是,这将起作用:
def show(x: Option[String]) = x match {
case Some(_) | None => "a"
}
Run Code Online (Sandbox Code Playgroud)
请注意,唯一的区别在于Some(_)与您的Some(s). 使用Some(s)没有多大意义,因为s无论如何你都不能重用它(如果None来了,s在那种情况下会是什么?)