Created
April 10, 2017 23:01
-
-
Save andyscott/29b71f8cbc8f9b2adb2bf57292484923 to your computer and use it in GitHub Desktop.
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
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