作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我广泛使用 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/
我想做一件简单的事情:monkey-patch datetime。我不能完全那样做,因为 datetime 是一个 C 类。 所以我写了下面的代码: from datetime import date
我喜欢新的 scalaz Memo 功能,但发现它缺少两件事:1)它隐藏了我需要访问的底层 Map——至少是所有值的列表,以及 2)我想要一个使用 val 实现的版本我在某处读到的 scala.col
我是一名优秀的程序员,十分优秀!