- Learning Scala Programming
- Vikash Sharma
- 174字
- 2021-06-30 19:07:53
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.
推薦閱讀
- Functional Python Programming
- 深入理解Android(卷I)
- Computer Vision for the Web
- Building Mobile Applications Using Kendo UI Mobile and ASP.NET Web API
- Visual Basic程序設計教程
- Microsoft Dynamics GP 2013 Reporting, Second Edition
- 重學Java設計模式
- Python機器學習基礎教程
- Clojure Reactive Programming
- Learning Probabilistic Graphical Models in R
- Python算法指南:程序員經典算法分析與實現
- 大數據分析與應用實戰:統計機器學習之數據導向編程
- 深入分布式緩存:從原理到實踐
- INSTANT Yii 1.1 Application Development Starter
- 時空數據建模及其應用