我有一个问题的后续问题,有和没有参数的重载方法定义的存在导致编译错误,这已经在这里讨论:为什么这个引用不明确?
回顾一下:
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)