Skip to content

Instantly share code, notes, and snippets.

@wedens
Created July 4, 2014 08:35
Show Gist options
  • Save wedens/acd86de71e5605493c8a to your computer and use it in GitHub Desktop.
Save wedens/acd86de71e5605493c8a to your computer and use it in GitHub Desktop.
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