Skip to content

Instantly share code, notes, and snippets.

@tlockney
Created February 23, 2011 03:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tlockney/839981 to your computer and use it in GitHub Desktop.
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
// 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/
@rschildmeijer
Copy link

neat

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment