Search code examples
scalaimplicit-conversionmethodology

How to (properly) enrich the standard library?


I would like to define an implicit conversion from Iterator[T] to a class that I have defined: ProactiveIterator[A].

The question isn't really how to do it but how to do it properly, i.e. where to place the method, so that it is as transparent and unobtrusive as possible. Ideally it should be as the implicit conversion from String to StringOps in scala.Predef If the conversion was from a class in the library to some other class, then it could be defined inside that class, but AFAIK that's not possible here.

So far I have considered to add an object containing these conversions, similarly to JavaConversions, but better options may be possible.


Solution

  • You don't really have much of a choice. All implicits must be contained within some sort of object, and imported with a wildcard import (you could import them individually, but I doubt you want that).

    So you'll have some sort of implicits object:

    package foo.bar
    
    object Implicits {
       implicit class ProactiveIterator[A](i: Iterator[A]) {
          ...
       }
    }
    

    Then you must explicitly import it wherever you use it:

    import foo.bar.Implicits._
    

    In my opinion, this is a good thing. Someone reading the code might not understand where your pimped methods are coming from, so the explicit import is very helpful.


    You can similarly place your implicits within a package object. You would have to import them the same way into other namespaces, but they would be available to classes within the same package.

    For example, using the following, anything within foo.bar will have this implicit class available:

    package foo
    
    package object bar {
       implicit class ProactiveIterator[A](i: Iterator[A]) {
          ...
       }
    }
    

    Elsewhere you would import foo.bar._ (which may or may not be as clean, depending on what's in bar).