gpt4 book ai didi

Scala:无样板的拉皮条

转载 作者:行者123 更新时间:2023-12-04 16:06:09 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com