Scala:返回布尔值的模式匹配的简短形式 [英] Scala: short form of pattern matching that returns Boolean
问题描述
我发现自己经常写这样的东西:
I found myself writing something like this quite often:
a match {
case `b` => // do stuff
case _ => // do nothing
}
是否有更短的方法来检查某个值是否与模式匹配?我的意思是,在这种情况下,我可以只写 if (a == b)//do stuff
,但是如果模式更复杂怎么办?就像在匹配列表或任意复杂性的任何模式时一样.我希望能够写出这样的东西:
Is there a shorter way to check if some value matches a pattern? I mean, in this case I could just write if (a == b) // do stuff
, but what if the pattern is more complex? Like when matching against a list or any pattern of arbitrary complexity. I'd like to be able to write something like this:
if (a matches b) // do stuff
我对 Scala 比较陌生,所以请原谅,如果我遗漏了一些重要的东西:)
I'm relatively new to Scala, so please pardon, if I'm missing something big :)
推荐答案
这正是我编写这些函数的原因,这些函数显然令人印象深刻,因为没有人提到它们.
This is exactly why I wrote these functions, which are apparently impressively obscure since nobody has mentioned them.
scala> import PartialFunction._
import PartialFunction._
scala> cond("abc") { case "def" => true }
res0: Boolean = false
scala> condOpt("abc") { case x if x.length == 3 => x + x }
res1: Option[java.lang.String] = Some(abcabc)
scala> condOpt("abc") { case x if x.length == 4 => x + x }
res2: Option[java.lang.String] = None
这篇关于Scala:返回布尔值的模式匹配的简短形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!