Skip to content

Instantly share code, notes, and snippets.

@nelanka
Last active November 4, 2018 16:42
Show Gist options
  • Save nelanka/a0321311942110a2022a to your computer and use it in GitHub Desktop.
Save nelanka/a0321311942110a2022a to your computer and use it in GitHub Desktop.
Typeclass
trait Foo[T] {
def foo(t: T): String
}
// Creates an implicit function that uses an implicit Foo[T] (evidence)
implicit def foo[T](t: T)(implicit ev: Foo[T]): String = ev.foo(t)
// Or using context bounds (choose one or the other depending on usage of the implicit evidence)
implicit def foo[T : Foo](t: T): String = implicitly[Foo[T]].foo(t)
// This is the Foo Typeclass for Int in implicit scope
implicit val FooInt = new Foo[Int] {
def foo(i: Int) = "Foo" * i
}
5.foo
foo(3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment