7

Is there a short syntax for string interpolation in Scala? Something like:

"my name is %s" < "jhonny"

Instead of

"my name is %s" format "jhonny"
Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
Johnny Everson
  • 8,343
  • 7
  • 39
  • 75

3 Answers3

9

No, but you can add it yourself:

scala> implicit def betterString(s:String) = new { def %(as:Any*)=s.format(as:_*) }
betterString: (s: String)java.lang.Object{def %(as: Any*): String}

scala> "%s" % "hello"
res3: String = hello

Note that you can't use <, because that would conflict with a different implicit conversion already defined in Predef.

Kim Stebel
  • 41,826
  • 12
  • 125
  • 142
4

In case you are wondering what syntax may be in the works

$ ./scala -nobootcp -Xexperimental
Welcome to Scala version 2.10.0.r25815-b20111011020241 

scala> val s = "jhonny"
s: String = jhonny

scala> "my name is \{ s }"
res0: String = my name is jhonny

Playing some more:

scala> "those things \{ "ne\{ "ts".reverse }" }"
res9: String = those things nest

scala> println("Hello \{ readLine("Who am I speaking to?") }")
Who am I speaking to?[typed Bozo here]Hello Bozo
huynhjl
  • 41,520
  • 14
  • 105
  • 158
3

I seem to remember Martin Odersky having been quoted with stating that string concatenation in the style presented in "Programming in Scala" is a useful approximation to interpolation. The idea is that without spaces you are only using a few extra characters per substitution. For example:

val x     = "Mork"
val y     = "Ork"

val intro = "my name is"+x+", I come from "+y

The format method provides a lot more power however. Daniel Sobral has blogged on a regex based technique too.

Don Mackenzie
  • 7,953
  • 7
  • 31
  • 32
  • The problem with concatenation is that sometimes you lose the 'view' for the whole string. e.g. "%s://%s" format (protocol, host) looks cleaner to me. – Johnny Everson Oct 10 '11 at 18:42