Scala:对重载定义的模糊引用 - 最好的消歧? [英] Scala: ambiguous reference to overloaded definition - best disambiguation?
问题描述
我有一个关于存在带参数和不带参数的重载方法定义会导致编译错误的问题的后续问题,这里已经讨论过:为什么这个引用含糊不清?
I have a follow-on question to the problem that the presence of overloaded method definitions with and without parameters leads to a compilation error, which is already discussed here: Why is this reference ambiguous?
总结:
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
有效的解决方案是为编译器提供预期的类型,如下所示:
A solution that works is to provide the compiler with the expected type, like so:
val s: String = B.foo
不幸的是,人们可能并不总是想要引入额外的变量(例如在断言中).在上面引用的较早文章的答案中至少推荐了两次的解决方案之一是调用带有空括号的方法,如下所示:
Unfortunately, one may not always want to introduce an extra variable (e.g. within an assertion). One of the solutions recommended at least twice in the answers to the earlier article referenced above was to invoke the method with empty parentheses, like so:
B.foo()
不幸的是,这会导致类似的编译器错误(Scala 2.9.0.1):
Unfortunately, this leads to a similar compiler error (Scala 2.9.0.1):
(s: String)String <and>
=> String
cannot be applied to ()
B.foo()
这是一个错误,还是推荐的解决方案有误?最终:有哪些选项可以简洁地做到这一点,例如:
Is this a bug, or was the recommended solution in error? And ultimately: what options are there to do this concisely, as in:
assert( B.foo == "whatever" )
代替
val expected : String = B.foo
assert( expected == "whatever" )
谢谢.
推荐答案
assert( (B.foo: String) == "whatever" )
这篇关于Scala:对重载定义的模糊引用 - 最好的消歧?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!