Skip to content

Instantly share code, notes, and snippets.

@butaji
Created October 20, 2015 19:29
Show Gist options
  • Save butaji/af39c784b554d1e26dc3 to your computer and use it in GitHub Desktop.
Save butaji/af39c784b554d1e26dc3 to your computer and use it in GitHub Desktop.
Some playing around Scala's type classes
def foo[A](a: A)(implicit ma: HasSize[A]) = {
ma.size(a)
}
def boo[A : HasSize](a: A) = {
implicitly[HasSize[A]].size(a)
}
trait HasSize[-A] { def size(a: A): Int }
class Shoe { def size = 5 }
implicit object ShoeSize extends HasSize[Shoe] {
def size(s: Shoe) = s.size + 1
}
implicit object ListSize extends HasSize[List[_]] {
def size(a: List[_]) = a.size
}
val l = foo(List(1, 2, 3, 4))
val bb = boo(List(1,2,3))
val s = new Shoe
val s1 = ShoeSize
val x = foo(s)(s1)
val x2 = foo(s)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment