【发布时间】:2012-10-24 17:49:18
【问题描述】:
我广泛使用Pimp my Library 模式,我想删除样板。例如,假设我有一些特质 PrettyPrint:
trait PrettyPrint { def prettyPrint: String }
如果我想拉皮条 Int 和 Double,我需要编写如下代码:
implicit def int2PrettyPrint(self: Int) =
new PrettyPrint { def prettyPrint = "Int: " + self }
implicit def double2PrettyPrint(self: Double) =
new PrettyPrint { def prettyPrint = "Double: " + self }
在上面,我将其归类为样板:1)隐式转换的名称,2)“new”关键字,3)也许是参数名称“self”,4)也许是“隐式”关键字。我宁愿写这样的东西:
@pimp[Int, PrettyPrint] { def prettyPrint = "Int: " + self }
@pimp[Double, PrettyPrint] { def prettyPrint = "Double: " + self }
在上述代码的右侧,名称“self”被假定为转换参数。
关于如何做到这一点的想法?
一些注意事项:
1) 如有必要,我愿意使用 Scala 2.10。
2) 据我所知,Scala 2.10 中的新隐式类还不够。这是因为每个隐式类只有一个隐式转换。换句话说,像下面这样的代码不会编译,因为 PrettyPrint 被声明了两次:
implicit class PrettyPrint(self: Int) = ...
implicit class PrettyPrint(self: Double) = ...
【问题讨论】:
-
@pr1001,是的。你有如何做到这一点的指针,或者有好的阅读链接吗?
-
到目前为止,宏无法进行全局可见的更改(例如添加公共成员或类)。我们可能会在 2.10.x 版本之一中添加此功能,但没有承诺。
-
@EugeneBurmako,那给我留下了什么?一个注解加一个编译器插件?
-
不是来自我,因为我并没有真正做 SBT/Eclipse 的事情。但鉴于我在 20 年前使用 C 代码生成器自动构建东西,我不得不想象它仍然是可能的。
-
@emchristiansen 看起来这是满足您所有要求的唯一方法。
标签: scala metaprogramming implicit-conversion scala-2.10 scala-macros