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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…