加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 从Object继承的方法呈现模糊不清

发布时间:2020-12-16 18:33:29 所属栏目:安全 来源:网络整理
导读:val x: AnyRef = 42 type mismatch: found Int(42) required: AnyRef Note: an implicit exists from scala.Int = java.lang.Integer ,but methods inherited from Object are rendered ambiguous . This is to avoid a blanket implicit which would conver
val x: AnyRef = 42

type mismatch: found Int(42) required: AnyRef

Note: an implicit exists from scala.Int => java.lang.Integer,but methods inherited from Object are rendered ambiguous. This is to avoid a blanket implicit which would convert any scala.Int to any AnyRef.

You may wish to use a type ascription: x: java.lang.Integer

我不明白强调的部分.什么方法变得模棱两可,怎么样?在Scala中,从Object继承的方法总是“呈现模糊”吗?这是一种特殊情况,方法在一种类型中以某种方式多次结束?我只是没有看到模棱两可的来源.

解决方法

Scala必须假装Int在继承层次结构中的位置与Java相同.这导致一些尴尬.

考虑方法notify.等待Int不起作用 – 这是一个原始的.等待新装箱的java.lang.Integer也不起作用,因为其他线程可能最终都有自己的单独装箱的整数.你只是不希望通知工作在Int – 这是错误的事情.

但是如果你有转换Int => java.lang.Integer没有任何异常,你可以在你的Int上调用notify.

为了防止这种通常错误的行为,由于歧义而无法解决转换的机制被劫持.这保持Int => java.lang.Integer用于转换Int所需的AnyRef(这将破坏继承层次结构),并阻止像42.notifyAll这样的东西工作,因为即使java.lang.Integer具有该方法,也不会注意推理机制它.

您看到的消息应该涵盖42.notify案例而不是42:AnyRef案例.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读