Using the magent pattern to get around a limitation with Scala’s overloading implementation.
I was writing some code recently that wanted to do this(somewhat contrived to simplify the example):
1 | def set(key: String, value: String)(implicit ttl: Duration = 1.hour): Int |
There’s some specific detail about how the Scala compiler implements default values for method parameters - that I havent’t investigated and probalby wouldn’t understand anyway - that makes it say the following:
1 | ... multiple overloaded alternatives of method set define default arguments. |
There’s clearly a way around this problem; don’t overload. So, I turned to the magnet pattern as popularized by the Spray library. It’s really just a specialized use for type classes that carries a cool name so it’s easy to talk about and reference. My use of the pattern, in this case, is even simpler because the return type of the method doesn’t vary with the magent instance. At any rate, here’s the deal:
1 | sealed trait ByteStringMagnet { |
Problem solved. The implicit conversions are resolved nicely because they’re right on the ByteStringMagnet
and, in general, you should never have to define an implicit conversion anywhere else (unless of course you need to extend the functionality from outside of the library).