Learning Scala Programming
上QQ阅读APP看书,第一时间看更新

The s interpolator

First, we'll look at the s interpolator. We've already seen how we can create a processed String with variables. Now, let's take an example that takes on expressions:

scala> val nextYearAge = s"Next Year, I'll complete ${age + 1}."
nextYearAge: String = Next Year, I'll complete 26.

Here, we used ${...} where a $ sign is followed by a pair of braces {<expression>}, consisting of the expression to be evaluated. It can be any expression. An arithmetic operation like we just did, or a method call:

scala> def incrementBy1(x: Int) = x + 1
incrementBy1: (x: Int)Int

scala> val nextYearAge = s"Next Year, I'll complete ${incrementBy1(age)}."
nextYearAge: String = Next Year, I'll complete 26.

Here, we defined a method named incrementBy1 that increments any Int passed by 1 and gives back the result. We've called that method from our interpolator. By the way, it's good to know that our interpolator s is a method just like any other operator in Scala. We're allowed to create our own interpolators in Scala.