Skip to content

Instantly share code, notes, and snippets.

@kmizu
Created August 14, 2011 04:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kmizu/1144569 to your computer and use it in GitHub Desktop.
Save kmizu/1144569 to your computer and use it in GitHub Desktop.
Hacking generalized type constraints.
> scalac GenTypeConstraints.scala
> scala GenTypeConstraints
2
FOOFOO
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