Created
June 8, 2016 02:05
-
-
Save sbcd90/0692506778af4589349c00c7eaae2da0 to your computer and use it in GitHub Desktop.
A simple typeclass sample
This file contains 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
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