Skip to content

Instantly share code, notes, and snippets.

@sofoklis
Last active December 12, 2015 04:18
Show Gist options
  • Save sofoklis/4713509 to your computer and use it in GitHub Desktop.
Save sofoklis/4713509 to your computer and use it in GitHub Desktop.
typeclasses
// 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
// 4.0 describe //This doesnt compile since we dont have a model in scope for Double
// 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