我广泛使用 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) 可能是“implicit”关键字。我宁愿这样写:
@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) = ...
最佳答案
你可以用不同的方式命名你的隐式类:
implicit class PrettyPrintInt(self: Int) = ...
implicit class PrettyPrintDouble(self: Double) = ...
关于Scala:无样板的拉皮条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13222853/