具有命名值的字符串格式 [英] String format with named values

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

问题描述

我正在寻找使用命名参数格式化字符串的惯用 scala 方法.我知道 String 方法格式,但它不允许指定命名参数,只能使用位置.

I'm searching for idiomatic scala way to format string with named arguments. I'm aware of the String method format, but it does not allow to specify named arguments, only positional are available.

简单例子:

val bob = "Bob"
val alice = "Alice"
val message = "${b} < ${a} and ${a} > ${b}"
message.format(a = alice, b = bob)

将消息定义为单独的值至关重要,因为我想从资源文件中加载它而不是直接在代码中指定.使用称为字符串插值的新 Scala 功能回答了许多类似的问题.但这并没有解决我的情况:我不能让编译器完成所有工作,因为资源文件是在运行时加载的.

Defining message as separate value is crucial, since I want to load it from resource file and not specify in the code directly. There are plenty of similar questions that was answered with the new scala feature called String Interpolation. But this does not address my case: I could not let the compiler do all the work, since resource file is loaded in the run time.

推荐答案

不清楚您所说的位置参数"是指通常的含义还是 Formatter 使用的参数索引"的含义.

It's not clear whether by "positional args" you mean the usual sense or the sense of "argument index" as used by Formatter.

scala> val bob = "Bob"
bob: String = Bob

scala> val alice = "Alice"
alice: String = Alice

scala> val message = "%2$s likes %1$s and %1$s likes %2$s" format (bob, alice)
message: String = Alice likes Bob and Bob likes Alice

你想:

scala> def f(a: String, b: String) = s"$b likes $a and $a likes $b"
f: (a: String, b: String)String

scala> f(b = bob, a = alice)
res2: String = Bob likes Alice and Alice likes Bob

您可以使用反射工具箱或脚本引擎来编译插值.

You can compile the interpolation with a reflective toolbox or the scripting engine.

scala> import scala.tools.reflect._
import scala.tools.reflect._

scala> val tb = reflect.runtime.currentMirror.mkToolBox()
tb: scala.tools.reflect.ToolBox[reflect.runtime.universe.type] = scala.tools.reflect.ToolBoxFactory$ToolBoxImpl@162b3d47

scala> val defs = s"""val a = "$alice" ; val b = "$bob""""
defs: String = val a = "Alice" ; val b = "Bob"

scala> val message = "${b} < ${a} and ${a} > ${b}"
message: String = ${b} < ${a} and ${a} > ${b}

scala> val msg = s"""s"$message""""
msg: String = s"${b} < ${a} and ${a} > ${b}"

scala> tb eval (tb parse s"$defs ; $msg")
res3: Any = Bob < Alice and Alice > Bob

scala> def f(a: String, b: String) = tb eval (tb parse s"""val a = "$a"; val b = "$b"; s"$message"""")
f: (a: String, b: String)Any

scala> f(a = alice, b = bob)
res4: Any = Bob < Alice and Alice > Bob

有点过分了.

但请考虑:

https://www.playframework.com/documentation/2.0/ScalaTemplates

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

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