为什么这个引用含糊不清?

编程入门 行业动态 更新时间:2024-10-05 21:15:27
本文介绍了为什么这个引用含糊不清?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 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() 应该也可以.

更多推荐

为什么这个引用含糊不清?

本文发布于:2023-11-26 10:09:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1633663.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不清

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!