Created
July 4, 2014 08:35
-
-
Save wedens/acd86de71e5605493c8a 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
import scala.reflect.macros.Context | |
import scala.language.experimental.macros | |
import scala.annotation.StaticAnnotation | |
object builderMacro { | |
def impl(c: Context)(annottees: c.Expr[Any]*): c.Expr[Any] = { | |
import c.universe._ | |
import Flag._ | |
val optType = typeOf[Option[Any]] | |
println(typeOf[String] <:< optType) | |
val result = { | |
annottees.map(_.tree).toList match { | |
case q"case class $name(..$args)" :: Nil => | |
val props = args.collect { | |
case q"$mods val $vname:$tpt = $expr" if tpt.tpe <:< typeOf[Option[_]] => | |
q"val $vname:$tpt = $expr" | |
case vd: ValDef => vd | |
} | |
val newName = TypeName(name.decoded + "Builder") | |
q""" | |
case class $newName(..$props) | |
""" | |
} | |
} | |
c.Expr[Any](result) | |
} | |
} | |
class builder extends StaticAnnotation { | |
def macroTransform(annottees: Any*) = macro builderMacro.impl | |
} | |
object Test extends App { | |
@builder | |
case class TestClass(x: Int = 4, y: Option[String] = Some("xx")) | |
val x = TestClassBuilder() | |
println(x.x) | |
println(x.yValue) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment