-
-
Save mandubian/6045407 to your computer and use it in GitHub Desktop.
#StructuralType without #reflection using #annotation trick imagined by @xeno_by (Eugene Burmako) originally https://gist.github.com/xeno-by/5967900 compatible #quasiquote
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
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE | |
Version 2, December 2004 | |
Copyright (C) 2013 YOUR_NAME_HERE <YOUR_URL_HERE> | |
Everyone is permitted to copy and distribute verbatim or modified | |
copies of this license document, and changing it is allowed as long | |
as the name is changed. | |
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE | |
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION | |
0. You just DO WHAT THE FUCK YOU WANT TO. |
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
import scala.annotation.StaticAnnotation | |
import scala.reflect.macros.Macro | |
import language.experimental.macros | |
class body(tree: Any) extends StaticAnnotation | |
trait Macros extends Macro { | |
import c.universe._ | |
def selFieldImpl = { | |
val field = c.macroApplication.symbol | |
val bodyAnn = field.annotations.filter(_.tpe <:< typeOf[body]).head | |
bodyAnn.scalaArgs.head | |
} | |
def mkObjectImpl(xs: c.Tree*) = { | |
val kvps = xs.toList map { case q"${_}(${Literal(Constant(name: String))}).->[${_}]($value)" => name -> value } | |
val fields = kvps map { case (k, v) => q"@body($v) def ${TermName(k)} = macro Macros.selFieldImpl" } | |
q"class Workaround { ..$fields }; new Workaround{}" | |
} | |
} | |
object mkObject { | |
def apply(xs: Any*) = macro Macros.mkObjectImpl | |
} |
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
object Test { | |
def main(args: Array[String]) = { | |
val foo = mkObject("x" -> "2", "y" -> 3) | |
println(foo.x) | |
println(foo.y) | |
// println(foo.z) => will result in a compilation error | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment