我在scala中有以下if:
我的列表是一些列表[字符串]
if (myList.isEmpty) return x > 5
if x < 0 return false
if (myList.head == "+") return foo()
if (myList.head == "-") return bar()
可以通过模式匹配来做到这一点吗?
这有点尴尬,但应该可以工作:
myList match {
case Nil => x > 5
case _ if x < 0 => false
case "+" :: _ => foo()
case "-" :: _ => bar()
}
请注意,您的匹配并不详尽。
对我来说,
这个更漂亮:
if(x > 0) {
myList.headOption match {
case Some("+") => foo()
case Some("-") => bar()
case None => x > 5
} else false
但我不确定这是否不符合逻辑流程(例如,当列表为空时提前退出 - 它是否在您的上下文中破坏了某些内容?),如果是这样,请随时说出来或投反对票。
是的,您可以在空列表上匹配,也可以在列表中的项目上进行匹配。如果您只需要一个条件而不匹配,请使用case _ if ...
:
def sampleFunction: Boolean =
lst match {
case Nil => x > 5
case _ if (x < 0) => false
case "+" :: _ => true
case "-" :: _ => false
case _ => true // return something if nothing matches
}