I've got a class from a library (specifically, com.twitter.finagle.mdns.MDNSResolver). I'd like to extend the class (I want it to return a Future[Set], rather than a Try[Group]).
I know, of course, that I could sub-class it and add my method there. However, I'm trying to learn Scala as I go, and this seems like an opportunity to try something new.
The reason I think this might be possible is the behavior of JavaConverters. The following code:
class Test {
var lst:Buffer[Nothing] = (new java.util.ArrayList()).asScala
}
does not compile, because there is no asScala method on Java's ArrayList. But if I import some new definitions:
class Test {
import collection.JavaConverters._
var lst:Buffer[Nothing] = (new java.util.ArrayList()).asScala
}
then suddenly there is an asScala method. So that looks like the ArrayList class is being extended transparently.
Am I understanding the behavior of JavaConverters correctly? Can I (and should I) duplicate that methodology?
Scala supports something called implicit conversions. Look at the following:
The second assignment does not work, because
Stringis expected, butIntis found. However, if you add the following into scope (just into scope, can come from anywhere), it works:Note that the name of the method does not matter.
So what usually is done, is called the pimp-my-library-pattern:
That allows you to call
coolMethodonFoo. This is used so often, that since Scala 2.10, you can write:which does the same thing but is obviously shorter and nicer.
So you can do:
And you'll be able to call
awesomeMethodon anyMDNSResolver, ifMyMDNSResolveris in scope.