Created
April 20, 2012 22:24
-
-
Save retronym/2432316 to your computer and use it in GitHub Desktop.
implicitly-either
This file contains hidden or 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> def implicitlyEitherImpl[A: c.TypeTag, B: c.TypeTag](c: reflect.makro.Context): c.Expr[Either[A, B]] = { | |
| def i[X](implicit X: c.TypeTag[X]): c.Tree = c.inferImplicitValue(X.tpe, silent = false) | |
| i[A] match { | |
| case c.mirror.EmptyTree => | |
| i[B] match { | |
| case c.mirror.EmptyTree => | |
| sys.error("Neither A nor B are available implicitly") | |
| case b => | |
| c.reify(Right[A, B](c.Expr[B](b).eval)) | |
| } | |
| case a => | |
| i[B] match { | |
| case c.mirror.EmptyTree => | |
| c.reify(Left[A, B](c.Expr[A](a).eval)) | |
| case b => | |
| sys.error("Both A and B are available implicitly") | |
| } | |
| } | |
| } | |
implicitlyEitherImpl: [A, B](c: scala.reflect.makro.Context)(implicit evidence$1: c.TypeTag[A], implicit evidence$2: c.TypeTag[B])c.Expr[Either[A,B]] | |
scala> def implicitlyEither[A, B] = macro implicitlyEitherImpl[A, B]implicitlyEither: [A, B]=> Either[A,B] | |
scala> implicitlyEither[Int, Int] | |
<console>:14: error: exception during macro expansion: | |
java.lang.RuntimeException: Neither A nor B are available implicitly | |
at scala.sys.package$.error(package.scala:27) | |
at .implicitlyEitherImpl(<console>:19) | |
implicitlyEither[Int, Int] | |
^ | |
scala> implicitlyEither[Int, String] | |
<console>:14: error: exception during macro expansion: | |
java.lang.RuntimeException: Neither A nor B are available implicitly | |
at scala.sys.package$.error(package.scala:27) | |
at .implicitlyEitherImpl(<console>:19) | |
implicitlyEither[Int, String] | |
^ | |
scala> implicitlyEither[Int, Int => Int] | |
res15: Right[Int,Int => Int] = Right(<function1>) | |
scala> implicitlyEither[Int => Int, Int => Int] | |
<console>:14: error: exception during macro expansion: | |
java.lang.RuntimeException: Both A and B are available implicitly | |
at scala.sys.package$.error(package.scala:27) | |
at .implicitlyEitherImpl(<console>:28) | |
implicitlyEither[Int => Int, Int => Int] | |
^ | |
scala> implicitlyEither[Int => Int, Int] | |
res18: Left[Int => Int,Int] = Left(<function1>) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment