Created
March 2, 2011 14:08
-
-
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.
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
object DSL { | |
implicit def MkDSLRichAnyOps[T](elem: T) = | |
new DSLRichAny(elem) | |
} |
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
class DSLRichAny[T](elem: T) { | |
def elemOf(that: Set[T]) = that contains elem | |
} |
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
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! | |
} | |
} |
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
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