Does Scala have a String variable substitution syntax like Ruby?

Scala FAQ: Does Scala have a String variable substitution syntax like Ruby?

UPDATE: If you're using Scala 2.10 or newer, see my new String interpolation in Scala 2.10 (embedding variables in strings) tutorial. If you're using Scala 2.9.x or older, continue with this article.

Unfortunately in Scala 2.9 you can't use something like the "#{}" syntax for substituting variables into strings like you can in Ruby, but you can use the format method of the String class like this:

val out = "%s is %d years old".format(name, age)

That may be a little longer than typing something like this in Ruby:

# ruby code
val out = "#{name} is #{age} years old"

but it's still pretty short, and also gives you the usual "printf" style formatting control that you're used to in pretty much every open source language (C, C++, Java, etc.).

If you want to experiment with this String "variable substitution" syntax in Scala, here's a little example class you can use for testing:

package devdaily

object StringFormattingTests extends App {
  
  val name = "Leonard Nimoy"
  val age = 81
  val out = "%s is %d years old".format(name, age)
  println(out)

}

You can find more information about how this String substitution/formatting approach works in my earlier Scala String formatting tutorial.

Post new comment

The content of this field is kept private and will not be shown publicly.