scala macros: Add function to class

我们两清 提交于 2019-12-01 19:39:11

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.

In case I'm not completely confused, simple overloading should provide the desired behavior? For instance, this would work:

trait MyTrait {
  def f(i: Int)
  def f(i: String)
}

class MyClass extends MyTrait {
  def f(i: Int) {
    println(i + " was an Int")
  }
  def f(s: String) {
    println(s + " was a String")
  }
}

// this allows:
val c = new MyClass()
c.f("hello")
c.f(42)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!