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
object Main
{
def main(args : Array[String])
{
val name = "GeeksforGeeks"
val articles = 32
val result = StringContext( "I have written " ,
" articles on " , "." ).s(articles, name)
println(result)
}
}
|
Output :
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
object Main
{
def main(args : Array[String])
{
implicit class Reverse ( val x : StringContext)
{
def revrs (args : Any*) : String =
{
val result = x.s(args : _ *)
result.reverse
}
}
val value = "GeeksforGeeks"
println (revrs "$value" )
}
}
|
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.
Last Updated :
11 Aug, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...