Created
February 23, 2011 03:49
-
-
Save tlockney/839981 to your computer and use it in GitHub Desktop.
Here's a very simplified example of hiding an implicit in a companion object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// initial version | |
import scala.collection.immutable.TreeSet | |
class TreeMember[A] { | |
// some really important stuff here, of course! ;~) | |
} | |
class Main { | |
implicit val treeOrder = new Ordering[TreeMember[A]] { | |
def compare(a: TreeMember[A], b: TreeMember[A]) = { | |
// elided for simplicity's sake | |
} | |
} | |
def main(args: Array[String]) { | |
val set = TreeSet[TreeMember[String]]() // need to have the ordering in scope here! | |
} | |
} | |
// new version | |
import scala.collection.immutable.TreeSet | |
class TreeMember[A] { } | |
object TreeMember { | |
// implicit is now nice and "hidden" inside the companion object | |
implicit def treeOrder[A]: Ordering[TreeMember[A]] = new Ordering[TreeMember[A]] { | |
def compare(a: TreeMember[A], b: TreeMember[A]) = { | |
// ye ol eliding | |
} | |
} | |
} | |
class Main { | |
def main(args: Array[String]) { | |
val set = TreeSet[TreeMember[String]]() // surprise, the ordering *is* in scope | |
} | |
} | |
// what's going on here is really pretty cool -- even though the compiler is looking for | |
// an implicit defining the Ordering[_] to use on the TreeSet, it will look in the companion | |
// object of the type parameters for that Ordering, allowing us to "hide" the Ordering in a | |
// more appropriate place. | |
// oh, and much thanks to Josh Suereth's Scala in Depth, which is where I learned about this | |
// technique. Go forth and buy the MEAP http://www.manning.com/suereth/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
neat