Johnny Everson
Johnny Everson

Reputation: 8601

Short for String.format in Scala

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"

Upvotes: 7

Views: 733

Answers (3)

huynhjl
huynhjl

Reputation: 41646

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

Upvotes: 4

Don Mackenzie
Don Mackenzie

Reputation: 7963

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.

Upvotes: 3

Kim Stebel
Kim Stebel

Reputation: 42047

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.

Upvotes: 9

Related Questions