Skip to content

Instantly share code, notes, and snippets.

@sbcd90
Created June 8, 2016 02:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sbcd90/0692506778af4589349c00c7eaae2da0 to your computer and use it in GitHub Desktop.
Save sbcd90/0692506778af4589349c00c7eaae2da0 to your computer and use it in GitHub Desktop.
A simple typeclass sample
object TypeClasses {
// the trait defined independent of thing(type A) & evidence(type CanFoo[A])
trait CanFoo[A] {
def foos(x: A): String
}
// object defined whose apply method takes an implicit param of type CanFoo[A]
object CanFoo {
def apply[A:CanFoo]: CanFoo[A] = implicitly
}
// A is of type Wrapper i.e. thing
case class Wrapper(wrapped: String)
// implicit object or evidence
// implicit ensures that there is "only" one object which extends CanFoo[Wrapper]
implicit object WrapperCanFoo extends CanFoo[Wrapper] {
def foos(x: Wrapper) = x.wrapped
}
// test method
def foo[A:CanFoo](thing: A) = CanFoo[A].foos(thing)
def main(args: Array[String]): Unit = {
println(foo(Wrapper("sbcd90")))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment