Skip to content

Instantly share code, notes, and snippets.

@mepcotterell
Created March 2, 2011 14:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mepcotterell/850983 to your computer and use it in GitHub Desktop.
Save mepcotterell/850983 to your computer and use it in GitHub Desktop.
Here's a small example of how to extends types by giving them more operations in Scala.
object DSL {
implicit def MkDSLRichAnyOps[T](elem: T) =
new DSLRichAny(elem)
}
class DSLRichAny[T](elem: T) {
def elemOf(that: Set[T]) = that contains elem
}
object DSLTestApp extends DSL {
def main(args: Array[String]): Unit = {
val set1 = Set(1, 2, 3, 4)
val set2 = Set("a", "b", "c", "d")
println(2 elemOf set1) // should print true
println(5 elemOf set1) // should print false
println("a" elemOf set2) // should print true
// println(1 elemOf set2) // won't compile; type mismatch!
}
}
These code snippets were used as examples in a blog post titled
"Implicit additions to types for DSL’s (Scala)." This post can be
found here at http://michaelcotterell.com/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment