Skip to content

Instantly share code, notes, and snippets.

@paulp
Created December 12, 2012 17:40
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulp/4269896 to your computer and use it in GitHub Desktop.
Save paulp/4269896 to your computer and use it in GitHub Desktop.
/** 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