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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s