Scala 运行时字符串插值/格式化 [英] Scala runtime string interpolation/formatting

查看:50
本文介绍了Scala 运行时字符串插值/格式化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何标准库工具可以在运行时进行字符串插值/格式化?我希望格式的行为与基于宏的 s"scala ${implementation} 完全相同,只是我的字符串格式是在运行时从配置文件加载的.

val format = config.getString("my.key")val stringContext = parseFormat(format)val res = stringContext.f("arg1", "arg2")

使用 parseFormat 返回一个 StringContext.

我想,在最坏的情况下,我可以在{}"序列上拆分字符串并使用这些部分来构造 StringContext.

//未测试def parseFormat(format: String): StringContext =new StringContext("""{}""".r.split(format): _*)

是否有我遗漏的明显解决方案,或者上述 hack 是否可以解决问题?

解决方案

A.从 Scala 2.10.3 开始,您不能使用 StringContext.f 除非您知道编译时的参数数量,因为 .f 方法是一个宏.>

B.使用 String.format,就像在 Java 的美好时光中一样.

Are there any standard library facilities to do string interpolation/formatting at runtime? I'd like the formatting to behave exactly the same as the macro based s"scala ${implementation} except that my string format is loaded at runtime from a config file.

val format = config.getString("my.key")
val stringContext = parseFormat(format)
val res = stringContext.f("arg1", "arg2")

with parseFormat returning a StringContext.

I imagine, worst case, I could just split the string on "{}" sequences and use the parts to construct the StringContext.

// untested
def parseFormat(format: String): StringContext =
  new StringContext("""{}""".r.split(format): _*)

Is there an obvious solution that I'm missing or would the above hack do the trick?

解决方案

A. As of Scala 2.10.3, you can't use StringContext.f unless you know the number of arguments at compile time since the .f method is a macro.

B. Use String.format, just like you would in the good ol' days of Java.

这篇关于Scala 运行时字符串插值/格式化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆