Skip to content

Instantly share code, notes, and snippets.

@andyscott
Created April 10, 2017 23:01
Show Gist options
  • Save andyscott/29b71f8cbc8f9b2adb2bf57292484923 to your computer and use it in GitHub Desktop.
Save andyscott/29b71f8cbc8f9b2adb2bf57292484923 to your computer and use it in GitHub Desktop.
abstract class LiteralValue[S] {
def value: S
}
object LiteralValue {
def apply[S](implicit ev: LiteralValue[S]): LiteralValue[S] = ev
implicit def makeLiteralValue[S <: Singleton]: LiteralValue[S] =
macro LiteralValueMacros.makeLiteralValue[S]
}
class LiteralValueMacros(val c: Context) {
import c.universe._
def makeLiteralValue[S <: Singleton](
implicit S: c.WeakTypeTag[S]
): c.Expr[LiteralValue[S]] = S.tpe.dealias match {
case ConstantType(const) =>
c.Expr[LiteralValue[S]](q"""
new LiteralValue[$S] {
override val value: $S = ${Literal(const)}
}
""")
case tpe => c.abort(c.enclosingPosition, s"$tpe isn't a singleton type")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment