scala:匹配函数声明

时间:2017-11-10 15:59:04

标签: scala

我是Scala的新手,所以解决方案可能很简单。然而,我一直在努力解决这个问题很长时间无法找到我的错误。这是我的代码的暂定(不工作)版本:

def fa (a: Int): Int = a
def fb (a: Int): Int = a+1
def fc (a: Int): Int = a+2


def myMatch (f: Int => Int): String = f match {
  case fa => "f is fa"
  case fb => "f is fb"
  case _ => "I dont know f"
}

我的测试:

myMatch(fa)
myMatch(fb)
myMatch(fc)

我想要的结果

res0: String = f is fa
res1: String = f is fb
res2: String = I dont know f

结果我获得:

res0: String = f is fa
res1: String = f is fa
res2: String = f is fa

警告:

Warning:(7, 9) patterns after a variable pattern cannot match (SLS 8.1.1)
If you intended to match against method fa in class A$A71, you must use backticks, like: case `fa` =>
  case fa => "f is fa"
       ^
Warning:(8, 15) unreachable code due to variable pattern 'fa' on line 11
If you intended to match against method fb in class A$A71, you must use backticks, like: case `fb` =>
  case fb => "f is fb"
             ^
Warning:(9, 14) unreachable code due to variable pattern 'fa' on line 11
  case _ => "I dont know f"
            ^
Warning:(8, 15) unreachable code
  case fb => "f is fb"
             ^

我曾尝试使用警告中所述的反引号,但写了类似

的内容
  case `fa` => "f is fa"

导致

Error:(7, 9) stable identifier required, but A$A73.this.fa found.
  case `fa` => "f is fa"
       ^

有什么想法吗?

感谢您的帮助

1 个答案:

答案 0 :(得分:4)

你很接近,唯一的一点是fa,fb和fc都是方法,但你只能对一个值进行模式匹配,这意味着你需要使用函数而不是方法(函数是值,方法不是) 。将它们重写为函数,它将按预期工作。

val fa = (a: Int) => a
val fb = (a: Int) => a+1
val fc = (a: Int) => a+2


def myMatch (f: Int => Int): String = f match {
  case `fa` => "f is fa"
  case `fb` => "f is fb"
  case _ => "I dont know f"
}

myMatch(fa) // f is fa
myMatch(fb) // f is fb
myMatch(fc) // I don't know f
myMatch((a: Int) => a) // I don't know f