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
They must be defined inside another 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. That is why.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With