Created
October 20, 2015 19:29
-
-
Save butaji/af39c784b554d1e26dc3 to your computer and use it in GitHub Desktop.
Some playing around Scala's type classes
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
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