Easy way of formatting strings in Scala

Scala offers two ways of formatting strings. This post describes both.

1. The .format method:

val t = "test"
val result = "This is a %s string".format(t)
println(result)

2. And string interpolator:

val t = "test"
println(s"This is a $t string")
println(result)

The second method does not work with functions or objects. For example:

def f(value : String) = value
println(s"This is a $f("test") string")
<console>:1: error: ')' expected but string literal found.

Today I found out is does, you just have to change the place holder from $ to ${}. Example:

def f(value : String) = value
println(s"This is a ${f("test")} string")
println(result)

Pretty cool right? Makes formatting strings very easy.

Leave a comment