- 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.
推薦閱讀
- AngularJS Testing Cookbook
- Learning ROS for Robotics Programming(Second Edition)
- Beginning Java Data Structures and Algorithms
- Visual C++串口通信開發(fā)入門與編程實(shí)踐
- 青少年美育趣味課堂:XMind思維導(dǎo)圖制作
- Selenium Design Patterns and Best Practices
- Essential Angular
- KnockoutJS Starter
- Unity 5 for Android Essentials
- 從0到1:Python數(shù)據(jù)分析
- QGIS By Example
- Mastering JavaScript Design Patterns(Second Edition)
- Learning FuelPHP for Effective PHP Development
- Android項(xiàng)目實(shí)戰(zhàn):手機(jī)安全衛(wèi)士開發(fā)案例解析
- C#程序設(shè)計(jì)(項(xiàng)目教學(xué)版)