Scala宏:将函数添加到类 [英] scala macros: Add function to class

查看:104
本文介绍了Scala宏:将函数添加到类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是scala宏的新手,并且正在使用scala 2.10.0-RC3.

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]()
}

是否可以使用Scala宏执行此操作?还是有另一种方法可以实现这一目标?

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

推荐答案

当前无法添加,修改或删除宏外部可见的定义. IE.您可以创建扩展本地的类或方法(例如,发出ClassDef树作为宏返回结果的一部分),但是没有影响外界的工具.

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.

但是,我们计划尝试使用 http://scalamacros.org/future.html 中大致概述的功能.另外,已经有一个可靠的原型可以生成新的顶级类.如果您想看一下,请与我联系以获取详细信息.

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.

这篇关于Scala宏:将函数添加到类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆