Skip to content

Instantly share code, notes, and snippets.

@pomu0325
Forked from kmizu/GenTypeConstraints.scala
Created August 14, 2011 16:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pomu0325/1145053 to your computer and use it in GitHub Desktop.
Save pomu0325/1145053 to your computer and use it in GitHub Desktop.
Hacking generalized type constraints.
object GenTypeConstraints {
abstract class =:=|[F,A,B] extends (F => Either[A,B])
object =:=| {
implicit def eqA[F,X]: =:=|[F,F,X] = new =:=|[F,F,X] {def apply(v:F) = Left(v)}
implicit def eqB[F,X]: =:=|[F,X,F] = new =:=|[F,X,F] {def apply(v:F) = Right(v)}
}
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
}
}
}
@pomu0325
Copy link
Author

汎用っぽくしてみたけど型パラメータが3つになってしまったのでinfixできなくてカッコワルい…

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment