Scala documentation states that implicit class "must be defined inside of another trait/class/object"
What is the reason for this constraint?
The referenced SIP describes implicit classes as being syntactic sugar for a class
and a def
.
Annotations on implicit classes default to attaching to the generated class and the method. For example,
@bar implicit class Foo(n: Int)
will desugar into:
@bar implicit def Foo(n: Int): Foo = new Foo(n) @bar class Foo(n:Int)
Since a def
must be within a trait/class/object, an implicit class, being partially "composed of" a def
, must also obey this condition.