官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 井冈山市| 苗栗市| 平塘县| 武强县| 墨江| 博湖县| 巫溪县| 栾城县| 湄潭县| 清原| 吴江市| 神池县| 浙江省| 广东省| 五河县| 奉新县| 英超| 信阳市| 黑龙江省| 大兴区| 平陆县| 武隆县| 吐鲁番市| 杭锦后旗| 洛扎县| 阿勒泰市| 横山县| 洪江市| 铜鼓县| 驻马店市| 萨迦县| 东安县| 楚雄市| 普兰店市| 日喀则市| 徐水县| 大悟县| 历史| 内江市| 通州区| 景洪市|