Scala | StringContext
StringContext is a class that is utilized in string interpolation, which permits the end users to insert the variables references without any intermediary in the processed String literals. This class supplies raw, s, and f methods by default as interpolators. The Linear Supertypes here are Serializable, java.io.Serializable, Product, Equals, AnyRef, and Any.
- An example of Using the available s-method as interpolator.
Example :// Scala program of the// StringContext// Creating objectobjectMain{// Main methoddefmain(args:Array[String]){// Assigning valuesvalname="GeeksforGeeks"valarticles=32// Applying StringContext with// s-methodvalresult=StringContext("I have written "," articles on ",".").s(articles, name)// Displays outputprintln(result)}}chevron_rightfilter_noneOutput :
I have written 32 articles on GeeksforGeeks.
Here, the StringContext.s method is utilized to extract the constant parts, translates the escape sequences contained and adds them with the values of the stated expression arguments.
The output here is returned like given below:"I have written " + (articles) + " articles on " + (name) + "."
Where, the variables articles and name are replaced by their values.
-
Creating our own interpolator : In order to supply our own String interpolator, We need to produce an implicit class that will attach a method to the StringContext class.
Example :// Scala program of StringContext// for creating our own string// interpolator// Creating objectobjectMain{// Main methoddefmain(args:Array[String]){// Using impicit class with// StringContextimplicitclassReverse (valx:StringContext){// Defining a methoddefrevrs (args:Any*):String={// Applying s-methodvalresult=x.s(args:_*)// Applying reverse methodresult.reverse}}// Assigning valuesvalvalue="GeeksforGeeks"// Displays reverse of the// stated stringprintln (revrs"$value")}}chevron_rightfilter_noneOutput :skeeGrofskeeG
Here, the defined method revrs passes each of its arguments to the s-method and then prints the reverse of the string stated.
Note : reverse is a function used here in order to reverse the string given.
Recommended Posts:
- Set in Scala | Set-2
- Set in Scala | Set-1
- Scala | Either
- Scala Map
- Scala Int %(x: Int) method with example
- Scala Set take() method with example
- BitSet in Scala
- Scala Set min() method with example
- Scala Set sum() method with example
- Scala | Variances
- HashSet In Scala
- Scala | REPL
- Scala | Traits
- Scala Stream
- Hello World in Scala
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




