scala macros: Add function to class

前端 未结 2 1204
借酒劲吻你
借酒劲吻你 2020-12-21 00:47

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 {
  d         


        
相关标签:
2条回答
  • 2020-12-21 01:04

    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)
    
    0 讨论(0)
  • 2020-12-21 01:12

    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.

    0 讨论(0)
提交回复
热议问题