Why is this reference ambiguous?

纵然是瞬间 提交于 2019-12-06 23:17:13

问题


import swing._

object PeerTest extends SimpleSwingApplication {
  def top = new MainFrame {
    val p = peer.getMousePosition 
  }
}

gives

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

but adding the type

val p: Point = peer.getMousePosition 

makes it ok. Why?

edit: causes problem:

class A {
  def value() = 123
}

class B extends A {
  def value(b: Boolean) = 42  
}

object Main extends App {
  println ((new B).value) 
}

doesn't cause problem:

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.


回答1:


There are two methods getMousePosition one without and one with a boolean parameter.

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.

Using getMousePosition() should work as well.




回答2:


A more direct way to refer to the desired overloaded alternative is by including the empty argument list.

peer.getMousePosition()


来源:https://stackoverflow.com/questions/7498677/why-is-this-reference-ambiguous

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!