带有嵌入变量的现有字符串上的Scala字符串插值器 [英] Scala String Interpolator on existing String with embedded Variables

查看:47
本文介绍了带有嵌入变量的现有字符串上的Scala字符串插值器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能遗漏了 Scala 字符串插值机制的一些基本内容.我想做什么:

I might be missing something basic with the Scala string interpolation mechanism. What I want to do:

// this could come from a config file, string here to demo
val brown = "BROWN"
val cow = "Moo"
val replaceInMe = "How Now ${brown} ${cow}"

//this does what I eventually want:
val output = s"How Now ${brown} ${cow}"

//But, since the variables 'brown' and 'cow' are defined,
//I really wold like to be able to do something like:
val output = s(replaceInMe) 

这甚至可能吗?

根据下面的第一个答案,它必须将变量 replaceInMe 作为输入.这里我将它定义为一个字符串,但它实际上是从配置文件中读取的一行.

Based on the first answer below, It has to take the variable replaceInMe as input. here I define it as a String, but it is actually a line read from a config file.

推荐答案

没有.documentation 清楚地表明您只能使用 string文字,而不是任何字符串对象.

No. The documentation makes it clear that you can only do this with string literals, and not any string object.

这是因为当编译器看到:

This is because when the compiler sees:

s"How Now ${brown} ${cow}"

它转换成:

new StringContext("How Now ", " ", "").s(brown, cow)

编译器无法使用任意标识符执行此操作,因为这些值可能是在运行时设置的,而不是在编译时设置.假设 replaceInMe 是从外部文件中提取的值.来自外部文件的字符串如何可能知道程序中的运行时变量?如果没有定义呢?对于字符串插值,这是通过编译错误处理的,这显然不会在运行时发生.在运行时,您需要另一种方法来处理缺失值.

The compiler can't do this with an arbitrary identifier, because the values are likely set at run time, and not compile time. Imagine that replaceInMe is a value pulled from an external file. How can a string from an external file possibly know about run time variables in the program? What if they weren't defined? With string interpolation this is dealt with via a compile error, which obviously can't happen at run time. At run time, you need another way to deal with missing values.

你最好使用某种配置库来处理这个问题.

You are better off using some sort of config library to handle this.

这篇关于带有嵌入变量的现有字符串上的Scala字符串插值器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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