Created
August 14, 2011 04:17
-
-
Save kmizu/1144569 to your computer and use it in GitHub Desktop.
Hacking generalized type constraints.
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
> scalac GenTypeConstraints.scala | |
> scala GenTypeConstraints | |
2 | |
FOOFOO |
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 GenTypeConstraints { | |
type ||[A, B] = Either[A, B] | |
implicit def any2Left[A, B](l: B): Either[B, A] = Left(l) | |
implicit def any2Right[A, B](r: B): Either[A, B] = Right(r) | |
def main(args: Array[String]) { | |
println(f(1)) | |
println(f("FOO")) | |
// compilation error println(f(1.0D)) | |
} | |
def f[T](v: T)(implicit ev: T => (String || Int)): String = { | |
ev(v) match { | |
case Left(s) => s + s | |
case Right(i) => (i + 1).toString | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment