函数的scala模式匹配
我正在寻找一种基于功能评估结果而不是val类型进行模式匹配的方法。例如函数的scala模式匹配,scala,pattern-matching,Scala,Pattern Matching,我正在寻找一种基于功能评估结果而不是val类型进行模式匹配的方法。例如 def f1(x:String):Boolean = if (x contains ("Helllo")) true else false val caller="Hello" caller match { case f1(caller) => println ("caller said hello") case _ => println ("caller did not say hello") }
def f1(x:String):Boolean = if (x contains ("Helllo")) true else false
val caller="Hello"
caller match
{
case f1(caller) => println ("caller said hello")
case _ => println ("caller did not say hello")
}
有什么想法吗?您想使用图案保护:
caller match
{
case x if f1(x) => println ("caller said hello")
case _ => println ("caller did not say hello")
}
我更喜欢在没有防护装置的情况下进行,这样会更快更干净:
f1(caller) match {
case true => ....
case false => ....
}
但是对于
Boolean
来说,更好地使用if/else表达式,它的字节码会更干净,速度也会更快一些听起来你基本上想要Haskell的扩展名。我明白你的意思,但如果只是字符串,那么u cna可能会使用正则表达式进行模式匹配。非常感谢@wingedsubmariner甚至不知道存在模式卫士。再次感谢。没问题@CruncherBigData:)守卫afaik的优点是它们不需要同时应用于所有情况。