Reputation: 13501
Considering that a implicit class "must be defined inside of another trait/class/object"1, how can a implicit conversion be defined globally?
The case is that I'd like to add a method to all Strings
(or Lists
) in my application, or at least to several packages of it.
Upvotes: 4
Views: 2514
Reputation: 44918
One cannot add anything to the "global" scope, neither in Java, nor in Scala.
However, in Scala one can define package objects
, which can contain methods that are used all over the package, and can be easily imported by the user.
This looks something like this: in the directory foo/bar/baz
one creates a file called package.scala
with the following content:
package foo.bar
package object baz {
implicit def incrediblyUsefulConversion(s: String) = ...
}
The user then can do the following in his code to activate the conversion:
import foo.bar.baz._
or maybe
import foo.bar.baz.incrediblyUsefulConversion
Of course, you can also use your own code in other packages, just like any other user.
Upvotes: 4