简体   繁体   中英

How could a “global implicit class” be defined in Scala?

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.

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM