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

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.

主站蜘蛛池模板: 洞口县| 曲周县| 东方市| 同江市| 海安县| 崇礼县| 什邡市| 嘉兴市| 南投县| 松江区| 永城市| 绥芬河市| 石柱| 虞城县| 泾源县| 孝感市| 彭州市| 常宁市| 灵川县| 微山县| 六安市| 保亭| 丹寨县| 揭西县| 彩票| 桂平市| 安康市| 舞钢市| 嘉义县| 珲春市| 荔波县| 江孜县| 宜丰县| 西安市| 阿坝| 鄂尔多斯市| 新宁县| 陵水| 香港 | 吕梁市| 黄陵县|