Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Short for String.format in Scala

Tags:

string

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"
like image 518
Johnny Everson Avatar asked Oct 10 '11 18:10

Johnny Everson


2 Answers

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.

like image 92
Kim Stebel Avatar answered Sep 21 '22 05:09

Kim Stebel


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
like image 23
huynhjl Avatar answered Sep 24 '22 05:09

huynhjl