简体   繁体   中英

variable string interpolation in scala

It's pretty clear, from the scala docs , that you can use string interpolation:

val name = "James"
println(s"Hello, $name")  // Hello, James

But, is it also possible to do this, where the format eg "Hello, $name" is in a variable?

I've tried something like this:

val name = "James"
val fmt = "Hello, $name"
println(s fmt)
println(s(fmt))

But, so far, nothing works. Is it even possible?

There's no easy way to get what you're after. For string interpolation to work, the compiler has to cut up the string literal into different parts and send them to StringContext for reconstruction. The compiler won't do that to a String variable.

It is possible to cut up String values yourself, and send them to StringContext , but you also need a way to translate a variable name (a String ) into the correct value.

See this answer to a similar question for an example how this might be done.

No this will not work in scala.

val name = "James"
val fmt = "Hello, $name"
println(s fmt)
println(s(fmt))

But you can do like below

println(s"$fmt")
OR
println(f"$fmt%s")

In string interpolation s always expects doubles quotes to be present as next character, SO s fmt or s(fmt) either will not work.

You can find more information here https://docs.scala-lang.org/overviews/core/string-interpolation.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM