Is there default(in SDK) scala support for string templating? Example: "$firstName $lastName"(named not numbered parameters) or even constructs like for/if. If there is no such default engine, what is the best scala library to accomplish this.
-
update: named parameters are preferred. – yura Jun 04 '11 at 21:53
-
possible duplicate of [Better String formatting in Scala](http://stackoverflow.com/questions/4051308/better-string-formatting-in-scala) – Always Asking Nov 13 '14 at 01:33
4 Answers
If you want a templating engine, I suggest you have a look at scalate. If you just need string interpolation, "%s %s".format(firstName, lastName)
is your friend.

- 41,826
- 12
- 125
- 142
In Scala 2.10 and up, you can use string interpolation
val name = "James"
println(s"Hello, $name") // Hello, James
val height = 1.9d
println(f"$name%s is $height%2.2f meters tall") // James is 1.90 meters tall

- 3,194
- 29
- 18
-
If I need to read the template "$name%s is $height%2.2f meters tall" from a file? Or just have it in a var/val? – Andrii Karaivanskyi Feb 15 '22 at 23:01
Complementing Kim's answer, note that Java's Formatter
accepts positional parameters. For example:
"%2$s %1$s".format(firstName, lastName)
Also, there's the Enhanced Strings plugin, which allows one to embed arbitrary expressions on Strings. For example:
@EnhanceStrings // enhance strings in this scope
trait Example1 {
val x = 5
val str = "Inner string arithmetics: #{{ x * x + 12 }}"
}
See also this question for more answers, as this is really a close duplicate.

- 1
- 1

- 295,120
- 86
- 501
- 681
-
+1 for the Enhanced Strings compiler plugin - no, it's not SDK, but it does a pretty good job – Kristian Domagala Jun 05 '11 at 23:21
This compiler plug-in has provided string interpolation for a while:
http://jrudolph.github.com/scala-enhanced-strings/Overview.scala.html
More recently, the feature seems to be making it into the scala trunk: https://lampsvn.epfl.ch/trac/scala/browser/scala/trunk/test/files/run/stringInterpolation.scala -- which generates some interesting possiblities: https://gist.github.com/a69d8ffbfe9f42e65fbf (not sure if these were possible with the plug-in; I doubt it).

- 2,155
- 15
- 32