我在尝试使用部分函数重载函数时遇到了一个奇怪的问题:
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
}
其次,我在这里发现了一个有趣的类似问题