Skip to content

Instantly share code, notes, and snippets.

@razie
Created September 15, 2011 20:09
Show Gist options
  • Save razie/1220329 to your computer and use it in GitHub Desktop.
Save razie/1220329 to your computer and use it in GitHub Desktop.
type classes
//============== 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