Scala 字符串格式命名参数(获胜者:最丑代码)
我想出了一个在 Scala 中使用命名参数的技巧。有更好的办法吗?有什么缺点?
<x>
|CREATE OR REPLACE FUNCTION myFunction({columns.map(column => column.name).
mkString(",\n")})
|RETURNS BOOLEAN AS $$
|BEGIN
| -- more stuff
|END;
|$$ LANGUAGE 'plpgsql';
|</x>.text.stripMargin
注意 XML 正文中的 & 符号;它们需要被“引用”为 &
或放置在大括号中,如 {"&"}
。我会赢得最丑代码奖吗? :-)
I came up with a trick to use named parameters in Scala. Is there a better way? What are the downsides?
<x>
|CREATE OR REPLACE FUNCTION myFunction({columns.map(column => column.name).
mkString(",\n")})
|RETURNS BOOLEAN AS $
|BEGIN
| -- more stuff
|END;
|$ LANGUAGE 'plpgsql';
|</x>.text.stripMargin
Watch out for ampersands in the XML body; they need to be "quoted" as &
or placed in braces like {"&"}
. Do I win a prize for ugliest code? :-)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为如果您需要这种规模的字符串格式化程序,则需要 Builder 或模板引擎,例如 Velocity。顺便说一句,我发现 Scala 对构建者和 DSL 有好处。
I think that if you need a string formater on this scale, you need a Builder or a templating engine, like Velocity. Incidentally, I've found Scala's good for builders and DSLs.
如果您不介意编译器插件,请尝试 Johannes Rudolph 的 Scala 增强版字符串。我非常喜欢它。
If you don't mind a compiler plugin, try Johannes Rudolph's Scala Enhanced Strings. I like it a lot.
好消息! Scala 2.10.0 引入了真正的函数式字符串插值!
这些文档可以在这里找到: http://docs.scala-lang.org /overviews/core/string-interpolation.html
这是一个快速示例:
在 Python 中,我曾经做过这样的事情:
现在,在 Scala 2.10.0+ 中,我们可以做到这一点!
还有一些格式字符串支持,这非常棒:
由于第二个示例具有一些最小的类型表达能力,因此它还为我们提供了一些基本的类型检查!
Good news! Scala 2.10.0 introduced real, functional string interpolation!
The docs are available here: http://docs.scala-lang.org/overviews/core/string-interpolation.html
Here's a quick sample:
In Python, I used to do things like:
now, in Scala 2.10.0+, we can do this!
There's also some format string support as well, which is pretty awesome:
Since the second example has some minimal type expressiveness, it also gives us some basic type checking as well!