Created
April 30, 2015 16:04
-
-
Save nuttycom/e4327adc21c840d77287 to your computer and use it in GitHub Desktop.
Capturing existential typeclasses in Scala
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
scala> trait Pet[A] { | |
| def blah(a: A): A | |
| } | |
defined trait Pet | |
scala> object IntPet extends Pet[Int] { | |
| def blah(i: Int) = i | |
| } | |
defined module IntPet | |
scala> object StringPet extends Pet[String] { | |
| def blah(s: String) = s + ", Esq." | |
| } | |
defined module StringPet | |
scala> trait Pet0 { type A; def a: A; def tc: Pet[A] } | |
defined trait Pet0 | |
scala> case class Pet1[X](a: X, tc: Pet[X]) extends Pet0 { type A = X } | |
defined class Pet1 | |
scala> val pets : List[Pet0] = List(Pet1(1, IntPet), Pet1("a", StringPet)) | |
pets: List[Pet0] = List(Pet1(1,IntPet$@6cbcf243), Pet1(a,StringPet$@29e6eb25)) | |
scala> pets.map { p => p.tc.blah(p.a) } | |
res2: List[Pet0#A] = List(1, a, Esq.) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment