Why should an implicit class in Scala be in another object / class / object?

Based on scala documentation: http://docs.scala-lang.org/overviews/core/implicit-classes.html , an implicit class has three limitations, and the very first one here, is

They must be defined inside another trait / class / object

What is the intuition / reason for explaining / justifying such a restriction?

+4
source share
1 answer

An implicit class is decomposed into a “normal” class and an implicit method that creates an instance of the class:

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

Corresponded 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 an object or class. That's why.

+10
source

All Articles