16

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. Is there plans to get implemented in next versions?

Thanks!

UPDATE

String interpolation is going to be in scala 2.10 which you can try out since scala 2.10.RC1 is out (20/10/2012). You can check out this SIP for scala 2.11 which states that interpolated strings in the pattern matcher will be valid syntax. With the new string interpolation you can do something like this:

val age = 28
val name = "Gerry"

s"My name is $name and I am $age years old"
res0: String = My name is Gerry and I am 28 years old

But try out the documentation on all the interpolators that are available at the moment. Note that you can define your own interpolators! Try this link for more info.

Community
  • 1
  • 1
Gerry
  • 5,326
  • 1
  • 23
  • 33

5 Answers5

22

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

Ben James
  • 121,135
  • 26
  • 193
  • 155
14

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).

Luigi Plinge
  • 50,650
  • 20
  • 113
  • 180
7

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
dips
  • 1,627
  • 14
  • 25
1

yes, there is string interpolation in current scala releases via compiler plugin see http://jrudolph.github.com/scala-enhanced-strings

OlegYch
  • 1,099
  • 7
  • 14
0

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"""
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250