Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
574 views
in Technique[技术] by (71.8m points)

reflection - scala macros: Add function to class

I'm new to scala macros and I'm using scala 2.10.0-RC3.

I want to write a macro that adds a function to a class. Usage example:

trait MyTrait {
  def addF = macro { /*add "def f = 3" to class*/ }
}

class MyClass extends MyTrait {
  addF //Adds the "def f" to MyClass
}

object Main {
  val t = new MyClass
  assert(t.f==3)
}

I need this in the following scenario. My first try didn't use macros but didn't work, because I can't inherit the same trait twice.

trait AddF[T] {
  def f(t: T) { /* ...do sthg ... */ }
}

class MyClass extends AddF[Int] with AddF[String]

With the macro solution I could write

class MyClass extends MyTrait {
  addF[Int]()
  addF[String]()
}

Is there a way to do this with scala macros? Or is there another way to achieve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is currently impossible to add, modify or remove definitions visible outside the macro. I.e. you can create a class or a method local to the expansion (e.g. emit a ClassDef tree as a part of the result returns by your macro), but there's no facility to affect the outside world.

However we plan to experiment with this functionality as roughly sketched in http://scalamacros.org/future.html. Also there's already a solid prototype that can generate new top-level classes. Contact me for details if you would like to take a look.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...