Last active
November 4, 2018 16:42
-
-
Save nelanka/a0321311942110a2022a to your computer and use it in GitHub Desktop.
Typeclass
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
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