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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.