Last active
December 12, 2015 04:18
-
-
Save sofoklis/4713261 to your computer and use it in GitHub Desktop.
typeclassexample
This file contains 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
// Start with a typed trait, which will form a small "concept" | |
trait Concept[T]{ | |
def describe : String | |
} | |
// Then the idea is to create models implementing this concept | |
// for the various types we want to use it | |
implicit class IntModel(n: Int) extends Concept[Int]{ | |
def describe : String = "The integer " + n | |
} | |
// Now we can use our model on integers like so | |
4 describe //> res0: String = The integer 4 | |
// We can also create models for other types like a list doubles etc | |
implicit class ListModel(l: List[Int]) extends Concept[List[Int]]{ | |
def describe : String = l mkString("A list of integers ", ", ", ".") | |
} | |
List(1,2,3,4,5) describe //> res1: String = A list of integers 1, 2, 3, 4, 5. | |
// Create another scope | |
{ | |
// Shadows the previous model | |
implicit class ListModel(l: List[Int]) extends Concept[List[Int]]{ | |
def describe : String = l mkString("My description of the integer list ", ", ", ".") | |
} | |
List(1,2,3,4,5) describe | |
} //> res2: String = My description of the integer list 1, 2, 3, 4, 5. | |
// One more scope | |
{ | |
// Shadows the previous model | |
implicit class IntModel(n: Int) extends Concept[Int]{ | |
def describe : String = "<p>" + n + "</p>" | |
} | |
5 describe | |
} //> res3: String = <p>5</p> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment