I wanted to ask if there is any type of string interpolation in Scala. I have made a search on the subject but \'till now I have found that there is no string interpolation.
It's not in the (released) scala library yet. But there is a SIP (Scala Improvement Process) for the addition of this feature:
http://docs.scala-lang.org/sips/pending/string-interpolation.html
You can do it C-style:
"Interpolate my %s here" format List(1,2,3)
//String = Interpolate my List(1, 2, 3) here
or
List(1,2,3) formatted "Interpolate my %s here"
You can use these on anything with a toString (i.e. anything)
case class Foo(n: Int)
Foo(42) formatted "Here is a %s !!!!"
//String = Here is a Foo(42) !!!!
although the former is more flexible in terms of enabling multiple interpolations in a single string (since it can take multiple arguments).
This days (Dec. 2016, Scala 2.12, five years later), you can write your own string interpolation.
See co.ntextu.al
Contextual is a small Scala library which allows you to define your own string interpolators—prefixed string literals like
uri"https://google.com"
which determine how they should be evaluated, at runtime and at compile-time, while only writing very ordinary user code: no macros!
For instance, contextual/examples/email.scala allows to check at compile time the validity of an email address.
import contextual.examples.email._
email"""info@scala.world"""
import contextual.examples.email._
email"""john.smith@hotmail.com"""
yes, there is string interpolation in current scala releases via compiler plugin see http://jrudolph.github.com/scala-enhanced-strings
I use the xml hack on scala 2.9
val age = 28
val name = "Gerry"
<a>My name is {name} and I am {age} years old</a>.text
res0: String = My name is Gerry and I am 28 years old