Scala:在参数中使用PartialFunction重载函数

时间:2016-03-01 20:53:26

标签: scala partialfunction

我尝试使用部分函数重载函数时遇到了一个奇怪的问题:

class Foo {
  def bar(pf: PartialFunction[String, Int]): Foo = ???
  def bar(zd: Int): Foo = ???
  def zed(pf: PartialFunction[String, Int]): Foo = ???
}

...
new Foo()
  .bar (0)
  .zed { case _ => 1 } // this line is OK
  .bar { case _ => 1 } // This line does not compile

我在REPL中粘贴了这段代码,并出现了一个奇怪的错误:

The argument types of an anonymous function must be fully known. (SLS 8.5)
Expected type was: ?
           .bar { case _ => 1 }
                ^

我已经在互联网上查看了这个错误的不同解释,但没有人谈论过载。据我所知,PartialFunction扩展为匿名函数。所以在这种情况下,这会导致类似:

object Test {
  new Foo()
    .bar (0)
    .zed { case _ => 1 }
    .bar { (x:String) => x match { case _ => 1 } }
}

但是一旦粘贴在REPL中,我就会收到另一个错误:

<console>:17: error: overloaded method value bar with alternatives:
  (zd: Int)Foo <and>
  (pf: PartialFunction[String,Int])Foo
 cannot be applied to (String => Int)
           .bar { (x:String) => x match { case _ => 1 } }
            ^

哪个好,因为没有签名在参数中使用匿名函数。那我错过了什么?我是否错误地扩展了部分功能?

感谢您的帮助!

修改

我刚刚发现问题可能来自于应该调用哪种方法的模糊性:

object Test {
  new Foo()
    .bar (0)
    .zed { case _ => 1 }
    .bar(PartialFunction({case _ => 1})) // This works
}

其次,我发现了一个有趣的类似问题here

2 个答案:

答案 0 :(得分:2)

正如反义词所说,在您链接的地方,它不是部分功能,而是匹配匿名功能的模式,可以是PartialFunctionFunction,具体取决于&# 39; s期望,问题在于它不能推断出类型,因为为了超载的目的而对arg进行类型检查没有预期类型&#34;。 &#34;形状&#34; test让函数文字工作。

scala> object X { def f(i: Int) = ??? ; def f(g: Int => Int) = ??? }
defined object X

scala> X.f { case i => 2 * i }
<console>:13: error: missing parameter type for expanded function
The argument types of an anonymous function must be fully known. (SLS 8.5)
Expected type was: ?
       X.f { case i => 2 * i }
           ^

scala> X.f(i => 2 * i)
scala.NotImplementedError: an implementation is missing
  at scala.Predef$.$qmark$qmark$qmark(Predef.scala:230)
  at X$.f(<console>:11)
  ... 28 elided

scala> X.f({ case i => 2 * i }: Int => Int)
scala.NotImplementedError: an implementation is missing
  at scala.Predef$.$qmark$qmark$qmark(Predef.scala:230)
  at X$.f(<console>:11)
  ... 28 elided

答案 1 :(得分:0)

这是此问题的explication。似乎编译器无法解析与匿名函数匹配的类型或模式。仅仅因为他们的'#34;形状&#34;无法解决。换句话说,重载不能与PartialFunctions一起使用。