Created
February 16, 2013 12:30
-
-
Save xeno-by/4966714 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
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 |
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
Eugene, what is the scope of this new method? Does it become global?