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

为什么Scala中的隐式类必须驻留在另一个特征/类/对象中?

发布时间:2020-12-16 18:20:56 所属栏目:安全 来源:网络整理
导读:根据 scala文档: http://docs.scala-lang.org/overviews/core/implicit-classes.html,隐式类有三个限制,我在这里引用的第一个是 They must be defined inside another trait/class/object 解释/证明这种限制的直觉/理由是什么? 解决方法 隐式类分解为“普
根据 scala文档: http://docs.scala-lang.org/overviews/core/implicit-classes.html,隐式类有三个限制,我在这里引用的第一个是

They must be defined inside another trait/class/object

解释/证明这种限制的直觉/理由是什么?

解决方法

隐式类分解为“普通”类和实例化类的隐式方法:

implicit class IntOps(i: Int) { def squared = i * i }

被重写为

class IntOps(i: Int) { def squared = i * i }
implicit def IntOps(i: Int) = new IntOps(i)

但是在Scala中,您无法在对象或类之外定义方法(def IntOps).这就是为什么.

(编辑:李大同)

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

    推荐文章
      热点阅读