yura
yura

Reputation: 14655

Scala support for string templates?

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?

Upvotes: 12

Views: 11919

Answers (4)

David Leppik
David Leppik

Reputation: 3304

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

Upvotes: 6

jsalvata
jsalvata

Reputation: 2205

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

Upvotes: 1

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297320

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.

Upvotes: 6

Kim Stebel
Kim Stebel

Reputation: 42045

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.

Upvotes: 11

Related Questions