Scala:过度定义的模糊参考 - 最好消除歧义?

Gre*_*idt 2 scala overloading ambiguity

我有一个问题的后续问题,有和没有参数的重载方法定义的存在导致编译错误,这已经在这里讨论:为什么这个引用不明确?

回顾一下:

 trait A { 
    def foo( s: String ) : String
    def foo : String = foo( "foo" )
 }
 object B extends A {
    def foo( s: String ) : String = s
 } 
 B.foo     // won't compile
Run Code Online (Sandbox Code Playgroud)

导致错误消息:

 error: ambiguous reference to overloaded function
 both method foo in object B of type(s: String)String
 and method foo in trait A of type => String
 match expected type Unit
 B.foo
Run Code Online (Sandbox Code Playgroud)

一个有效的解决方案是为编译器提供预期的类型,如下所示:

 val s: String = B.foo
Run Code Online (Sandbox Code Playgroud)

不幸的是,人们可能并不总是想要引入额外的变量(例如在断言中).在上面引用的早期文章的答案中至少推荐两次的解决方案之一是使用空括号调用方法,如下所示:

 B.foo()
Run Code Online (Sandbox Code Playgroud)

不幸的是,这会导致类似的编译器错误(Scala 2.9.0.1):

 (s: String)String <and>
 => String
 cannot be applied to ()
 B.foo()
Run Code Online (Sandbox Code Playgroud)

这是一个错误,还是建议的错误解决方案?最终:有什么选择可以简洁地做到这一点,如:

 assert( B.foo == "whatever" )
Run Code Online (Sandbox Code Playgroud)

代替

 val expected : String = B.foo
 assert( expected == "whatever" )
Run Code Online (Sandbox Code Playgroud)

谢谢.

agi*_*eel 6

assert( (B.foo: String) == "whatever" )
Run Code Online (Sandbox Code Playgroud)