Created
December 12, 2012 17:40
-
-
Save paulp/4269896 to your computer and use it in GitHub Desktop.
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
/** Constructing "singleton types" from compile-time literals | |
* | |
* val x = Example.foo(42) | |
* val y: x.T = 42 // compiles | |
* val z: x.T = 43 // doesn't | |
* | |
*/ | |
package s | |
import scala.language.experimental.macros | |
import scala.reflect.macros.Context | |
class Nat[In] { type T = In } | |
object NatMe { | |
def foo(s: Int): Any = macro foo_impl | |
def foo_impl(c: Context)(s: c.Expr[Int]) = { | |
import c.universe._ | |
s.tree match { | |
case Literal(const: Constant) => c.Expr(New(appliedType(typeOf[Nat[_]].typeConstructor, ConstantType(const) :: Nil))) | |
case _ => c.abort(c.enclosingPosition, "Not a literal") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment