paweln1986 paweln1986 - 1 year ago 100
Scala Question

Scala string interpolation and evaluate expression

I am diving into Scala's string interpolation feature and I wonder if it is safe to use it. String interpolation allows us to evaluate expression like:

println(s"Hello World! ${for (i <- 1 to 100) println(s"other values $i")}")

My doubt is if we should evaluate expression in interpolated string. I see a lot of Scala code where other developers are using this feature like in example and don't know if this is correct and safe.

Answer Source

I would never use it and I would not want my colleagues to use it.

Two things are essentially off:

  • String interpolation is a nice feature because it makes concatenation of values easy to read... unless you stick an entire scala program in there :)
  • Not only there's a complex expression in there, but you're using a side-effect, so in the process of evaluating the interpolation 100 values will be printed. So you get

    other values 1
    other values 2
    other values 100
    Hello World! ()

Where the () is the return value of the for-comprehension, i.e. Unit.

I would save myself (and my colleagues) tremendous headaches and just do

println(s"Hello World!")
for (i <- 1 to 100) {
  println(s"other values $i")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download