Created
September 15, 2011 20:09
-
-
Save razie/1220329 to your computer and use it in GitHub Desktop.
type classes
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
//============== the Type Class version | |
trait Eq[A] { // the type trait | |
def areTheSame(a: A, b: A): Boolean | |
} | |
case class Student(name: String) // better decoupling - extends nothing | |
object EqImplementations { // the implementations for different classes | |
implicit object EqStudent extends Eq[Student] { | |
override def areTheSame(a: Student, b: Student) = a.name == b.name | |
} | |
} | |
// all it says is that there must be an Eq implementation for A, somewhere in context | |
def member[A: Eq](a: A, container: List[A]) = | |
container.exists(implicitly[Eq[A]].areTheSame(_, a)) | |
import EqImplementations._ // bring it in context | |
member(Student("John"), List(Student("John"))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment