2

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 e.g. "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?

3
  • What is this s? Commented Jul 25, 2019 at 4:28
  • I think s resolves to a function scala-lang.org/api/current/scala/StringContext.html Commented Jul 25, 2019 at 4:31
  • 1
    I see. You are referring to the macro prefix. No it doesn't work that way. The string literal has to be presented for the macro expansion. Commented Jul 25, 2019 at 6:38

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.