本文介绍了为什么这个引用含糊不清?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
import swing._
object PeerTest extends SimpleSwingApplication {
def top = new MainFrame {
val p = peer.getMousePosition
}
}
给予
error: ambiguous reference to overloaded definition, both method getMousePosition in class Container of type (x$1: Boolean)java.awt.Point and method getMousePosition in class Component of type ()java.awt.Point match expected type ? val p = peer.getMousePosition但添加类型
val p: Point = peer.getMousePosition没问题.为什么?
导致问题:
class A { def value() = 123 } class B extends A { def value(b: Boolean) = 42 } object Main extends App { println ((new B).value) }不会引起问题:
class A { def value() = 123 def value(b: Boolean) = 42 } class B extends A {} object Main extends App { println ((new B).value) }所以我认为答案必须解释为什么只有当方法在不同的类中时才会发生.
So I think the answer has to explain why it only occurs when the methods are in different classes.
推荐答案getMousePosition 有两种方法,一种没有布尔参数,一种带有布尔参数.
There are two methods getMousePosition one without and one with a boolean parameter.
如果没有类型注解,Scala 不知道您是否想要在一个参数(Function1 对象)中引用该方法,或者您是否想要调用没有参数的方法(导致 点).
Without a type annotation Scala does not know if you want a reference to the method in one parameter (a Function1 object) or if you want to invoke the one without parameters (resulting in a Point).
指定预期类型可以阐明您的意图.
Specifying the expected type clarifies your intend.
使用 getMousePosition() 应该也可以.
更多推荐
为什么这个引用含糊不清?
发布评论