1

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

回顾一下:

 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

导致错误消息:

 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

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

 val s: String = B.foo

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

 B.foo()

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

 (s: String)String <and>
 => String
 cannot be applied to ()
 B.foo()

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

 assert( B.foo == "whatever" )

代替

 val expected : String = B.foo
 assert( expected == "whatever" )

谢谢。

4

2 回答 2

6
assert( (B.foo: String) == "whatever" )
于 2011-10-11T05:28:41.130 回答
2

您可以在第二个foo定义中添加空括号:

trait A { 
  def foo( s: String ) : String
  def foo() : String
}

然后,您可以按照其他地方的说明删除歧义:

assert( B.foo() == "whatever" )
于 2011-10-11T06:52:41.273 回答