简体   繁体   English

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

[英]Why implicit class in Scala must reside in another trait/class/object?

Based on the scala documentation: http://docs.scala-lang.org/overviews/core/implicit-classes.html , the implicit class has three restrictions, and the very first one, I quote here, is 基于scala文档: http//docs.scala-lang.org/overviews/core/implicit-classes.html ,隐式类有三个限制,我在这里引用的第一个是

They must be defined inside another trait/class/object 它们必须在另一个trait / class / object中定义

What is the intuition/reason to explain/justify such a restriction? 解释/证明这种限制的直觉/理由是什么?

An implicit class decomposes into a "normal" class and an implicit method that instantiates the class: 隐式类分解为“普通”类和实例化类的隐式方法:

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

Is rewritten as 被重写为

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

But in Scala, you cannot define a method ( def IntOps ) outside of an object or a class. 但是在Scala中,您无法在对象或类之外定义方法( def IntOps )。 That is why. 这就是为什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM