Scala:无样板的拉皮条

标签 scala metaprogramming implicit-conversion scala-2.10 scala-macros

我广泛使用 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/

相关文章:

Scala 集合将 var 映射到另一个值

c# - 为多行 lambda 创建表达式树的 Roslyn 流畅语法

斯卡拉宏 : Add function to class

c++ - 为什么函数重载不会导致歧义错误? (c++)

c++ - 为什么 std::string 不提供到 const char* 的转换?

c# - 抽象泛型隐式转换为派生类型,错误?

scala - 使用 Future 进行快速排序最终陷入僵局

scala - 变换/遍历 Shapeless 的 HMap

scala - 自动将 JavaBeans 包装/转换为 case 类

c++创建编译时未知类型的连续数组