Skip to content

Instantly share code, notes, and snippets.

@xeno-by
Created February 16, 2013 12:30
Show Gist options
  • Save xeno-by/4966714 to your computer and use it in GitHub Desktop.
Save xeno-by/4966714 to your computer and use it in GitHub Desktop.
13:29 ~/Projects/Kepler_introduce-member/sandbox (topic/introduce-member)$ cat Macros.scala
import scala.reflect.macros.Context
import language.experimental.macros
object Macros {
def impl(c: Context)(target: c.Tree, name: c.Tree, code: c.Tree) = {
import c.universe._
val Literal(Constant(targetType: Type)) = c.typeCheck(target)
val Literal(Constant(methodName: String)) = name
val Function(methodParams, methodBody) = code
val method = DefDef(NoMods, TermName(methodName), Nil, List(methodParams), TypeTree(), methodBody)
c.introduceMember(targetType.typeSymbol, method)
c.literalUnit
}
def addMethod(target: _, name: String, code: _) = macro impl
}
13:29 ~/Projects/Kepler_introduce-member/sandbox (topic/introduce-member)$ cat Test.scala
// class C
object Test extends App {
Macros.addMethod(classOf[C], "foo", (x: Int) => x + 2)
println(new C().foo(2))
}
class C
13:29 ~/Projects/Kepler_introduce-member/sandbox (topic/introduce-member)$ scalac Macros.scala && scalac Test.scala && scala Test
4
@fujohnwang
Copy link

cool~

@VladUreche
Copy link

Eugene, what is the scope of this new method? Does it become global?

@xeno-by
Copy link
Author

xeno-by commented Feb 19, 2013

No, the introduced member becomes the proper member of the provided owner class, trait or object.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment