The Wayback Machine - https://web.archive.org/web/20240910183413/https://www.geeksforgeeks.org/scala-string-interpolation/
Open In App

Scala | String Interpolation

Last Updated : 26 Feb, 2019
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

String Interpolation refers to substitution of defined variables or expressions in a given String with respected values. String Interpolation provides an easy way to process String literals. To apply this feature of Scala, we must follow few rules:

  1. String must be defined with starting character as s / f /raw.
  2. Variables in the String must have ‘$’ as prefix.
  3. Expressions must be enclosed within curly braces ({, }) and ‘$’ is added as prefix.

Syntax:

// x and y are defined
val str = s"Sum of $x and $y is ${x+y}"

Types of String Interpolator

  1. s Interpolator: Within the String, we can access variables, object fields, functions calls, etc.

    Example 1: variables and expressions:




    // Scala program
    // for s interpolator
      
    // Creating object
    object GFG
    { 
        // Main method
        def main(args:Array[String])
        {
          
            val x = 20
            val y = 10
          
            // without s interpolator
            val str1 = "Sum of $x and $y is ${x+y}"
      
            // with s interpolator
            val str2 = s"Sum of $x and $y is ${x+y}"
          
            println("str1: "+str1)
            println("str2: "+str2)
        }
    }

    
    

    Output:

    str1: Sum of $x and $y is ${x+y}
    str2: Sum of 20 and 10 is 30

    Example 2: function call




    // Scala program
    // for s interpolator
      
    // Creating object
    object GFG
    { 
        // adding two numbers
        def add(a:Int, b:Int):Int
        =
        { 
            a+b 
        }
          
        // Main method
        def main(args:Array[String])
        {
          
            val x = 20
            val y = 10
          
            // without s interpolator
            val str1 = "Sum of $x and $y is ${add(x, y)}"
      
            // with s interpolator
            val str2 = s"Sum of $x and $y is ${add(x, y)}"
          
            println("str1: " + str1)
            println("str2: " + str2)
        }
    }

    
    

    Output:

    str1: Sum of $x and $y is ${add(x, y)}
    str2: Sum of 20 and 10 is 30
  2. f Interpolator: This interpolation helps in formatting numbers easily.

    To understand how format specifiers work refer Format Specifiers.

    Example 1: printing upto 2 decimal place:




    // Scala program
    // for f interpolator
      
    // Creating object
    object GFG
    { 
        // Main method
        def main(args:Array[String])
        {
          
            val x = 20.6
          
            // without f interpolator
            val str1 = "Value of x is $x%.2f"
      
            // with f interpolator
            val str2 = f"Value of x is $x%.2f"
          
            println("str1: " + str1)
            println("str2: " + str2)
          
        }
    }

    
    

    Output:

    str1: Value of x is $x%.2f
    str2: Value of x is 20.60

    Example 2: setting width in integers:




    // Scala program
    // for f interpolator
      
    // Creating object
    object GFG
    { 
        // Main method
        def main(args:Array[String])
        {
          
            val x = 11
          
            // without f interpolator
            val str1 = "Value of x is $x%04d"
      
            // with f interpolator
            val str2 = f"Value of x is $x%04d"
          
            println(str1)
            println(str2)
        }
    }

    
    

    Output:

    Value of x is $x%04d
    Value of x is 0011

    If we try to pass a Double value while formatting is done using %d specifier, compiler outputs an error. In case of %f specifier, passing Int is acceptable.

  3. raw Interpolator: String Literal should start with ‘raw’. This interpolator treats escape sequences same as any other character in a String.
    Example :printing escape sequence:




    // Scala program
    // for raw interpolator
      
    // Creating object
    object GFG
    { 
        // Main method
        def main(args:Array[String])
        {
              
            // without raw interpolator
            val str1 = "Hello\nWorld"
      
            // with raw interpolator
            val str2 = raw"Hello\nWorld"
          
            println("str1: " + str1)
            println("str2: " + str2)
        }
    }

    
    

    Output:

    str1: Hello
    World
    str2: Hello\nWorld


Previous Article
Next Article

Similar Reads

Scala String indexOf(String str) method with example
The indexOf(String str) method is utilized to return the index of the sub-string which occurs first in the string stated. Method Definition: indexOf(String str) Return Type: It returns the index of the sub-string which is specified in the argument of the method. Example #1: // Scala program of int indexOf() // method // Creating object object GfG {
1 min read
Scala String startsWith(String prefix, int toffset) method with example
The startsWith(String prefix, int toffset) method is utilized to check if the stated string starts with the prefix or not that is being specified by us at the specified index. Method Definition: Boolean startsWith(String prefix, int toffset) Return Type: It returns true if the string starts with the specified prefix at the specified index else it r
1 min read
Scala String lastIndexOf(String str, int fromIndex) method with example
The lastIndexOf(String str, int fromIndex) method is utilized to return the index of the last appearance of the sub-string we specify in the argument from the index specified from right to left from the stated string. Method Definition: int lastIndexOf(String str, int fromIndex) Return Type: It returns the index of the last appearance of the sub-st
1 min read
Scala String indexOf(String str, int fromIndex) method with example
The indexOf(String str, int fromIndex) method is utilized to return the index of the sub-string which occurs first from the index we specify in the string stated. Method Definition: int indexOf(String str, int fromIndex) Return Type: It returns the index of the sub-string from the index specified in the argument. Example #1: // Scala program of int
1 min read
Scala String regionMatches(int toffset, String other, int offset, int len) method with example
The regionMatches(int toffset, String other, int offset, int len) method is used to check if two string regions are equal or not. However, here ignoreCase is not included. Method Definition:Boolean regionMatches(int toffset, String other, int offset, int len) Return Type: It returns true if two string region matches else it returns false. Example #
1 min read
Scala String lastIndexOf(String str) method with example
The lastIndexOf(String str) method is utilized to return the index of the last appearance of the sub-string we specify in the argument from the stated string. Method Definition: int lastIndexOf(String str) Return Type: It returns the index of the last appearance of the sub-string specified in the argument. Example #1: // Scala program of int lastIn
1 min read
Scala String startsWith(String prefix) method with example
The startsWith(String prefix) method is utilized to check if the stated string starts with the prefix or not that is being specified by us. Method Definition: Boolean startsWith(String prefix) Return Type: It returns true if the string starts with the specified prefix else it returns false. Example: 1# // Scala program of startsWith() // method //
1 min read
Scala String split(String regex, int limit) method with example
The split(String regex, int limit) method is same as split(String, regex) method but the only difference here is that you can limit the number of elements in the resultant Array. Method Definition: String[] split(String regex, int limit) Return Type: It returns a String array where, the number of elements in the Array are specified and the last ele
1 min read
How to convert future string to string in Scala?
In this article, we will convert future string to string in Scala. We use three different methods to convert future string to string in Scala. Table of Content What is the future string in Scala?Methods to convert future string to string in Scala:What is the future string in Scala?"Future" is a construct for asynchronous programming in Scala. It is
4 min read
Scala String contentEquals() method with example
The contentEquals() method is utilized to compare a string to the content of StringBuffer. Method Definition: Boolean contentEquals(StringBuffer sb) Return Type: It returns true if the content is equal to the stated string else it returns false. Example #1: // Scala program of contentEquals() // method // Creating object object GfG { // Main method
1 min read
Scala String substring(int beginIndex, int endIndex) method with example
The substring(int beginIndex, int endIndex) method is utilized to find the sub-string from the stated String which starts and ends with the index specified. Method Definition: String substring(int beginIndex, int endIndex) Return Type: It returns string which is the part of the stated String. Note: It is same as sub-sequence method but the only dif
1 min read
Scala String
A string is a sequence of characters. In Scala, objects of String are immutable which means a constant and cannot be changed once created. Creating a String in Scala There are two ways to create a string in Scala: Here, when the compiler meet to a string literal and creates a string object str. Syntax: var str = "Hello! GFG" or val str = "Hello! GF
4 min read
Program to convert Java Set to a String in Scala
A java Set can be converted to a String in Scala by utilizing toString method of Java in Scala. Here, we need to import Scala’s JavaConversions object in order to make this conversions work. Now, lets see some examples and then discuss how it works in details. Example:1# // Scala program to convert Java set // to a String in Scala // Importing Scal
2 min read
Scala String subSequence() method with example
The subSequence() method is utilized to find the sub-sequence from the given String, And this sub-sequence starts and ends with the index we specify. Method Definition: CharSequence subSequence(int beginIndex, int endIndex) Return Type: It returns the resultant sub-sequence. Example: 1# // Scala program of subSequence() // method // Creating object
1 min read
Program to convert Java Set of doubles to a String in Scala
A java Set of doubles can be converted to a String in Scala by utilizing toString method of Java in Scala. Here, you need to import Scala’s JavaConversions object in order to make this conversions work. Now, lets see some examples and then discuss how it works in details. Example:1# // Scala program to convert Java set // to a String in Scala // Im
1 min read
Program to convert Java Set of shorts to a String in Scala
A java Set of shorts can be converted to a String in Scala by utilizing toString method of Java in Scala. Here, you need to import Scala’s JavaConversions object in order to make this conversions work. Now, lets see some examples and then discuss how it works in details. Example:1# // Scala program to convert Java set // to a String in Scala // Imp
1 min read
String concatenation in Scala
A string is a sequence of characters. In Scala, objects of String are immutable which means a constant and cannot be changed once created. when a new string is created by adding two strings is known as a concatenation of strings. Scala provides concat() method to concatenate two strings, this method returns a new string which is created using two s
2 min read
Scala String equalsIgnoreCase() method with example
The equalsIgnoreCase() method is utilized to check if the stated string and object are equal by ignoring the case difference. Method Definition: Boolean equalsIgnoreCase(String anotherString) Return Type: It returns true if the string is same as the object stated by ignoring the case difference, else it returns false. Example #1: // Scala program o
1 min read
Scala String endsWith() method with example
The endsWith() method is utilized to check if the stated string ends with the suffix stated in the argument. Method Definition: Boolean endsWith(String suffix) Return Type: It returns true if the string ends with the suffix stated else it returns false. Example #1: // Scala program of endsWith() // method // Creating object object GfG { // Main met
1 min read
Scala String compareToIgnoreCase() method with example
The compareToIgnoreCase() method is utilized to compare two strings like compareTo method but here the case (upper or lowercase) difference is ignored while comparing. Method Definition:int compareToIgnoreCase(String str) Return Type:It is same as compareTo() method but here only case difference is ignored. Example: 1# // Scala program of compareTo
1 min read
Scala String charAt() method with example
The charAt() method is utilized to return the character of the index passed in the argument. Method Definition: char charAt(int index) Return Type: It returns char for the index given in the argument. Example #1: // Scala program of charAt() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a String
1 min read
Scala String equals() method with example
The equals() method is utilized to check if the stated string and object are equal. Method Definition: Boolean equals(Object anObject) Return Type: It returns true if the string is same as the object stated else it returns false. Example #1: // Scala program of equals() // method // Creating object object GfG { // Main method def main(args:Array[St
1 min read
Scala String compareTo() method with example
The compareTo() method is utilized to compare a string with another string. Some points to remember: Here, If a string(S1) is same as string(S2) in comparison then this method returns zero. If S1 is less than S2 then a negative number is returned which is the difference of character value. If S1 is greater than S2 then a positive number is returned
2 min read
Scala String getBytes() method with example
The getBytes() method is utilized to encode a stated string into a series of bytes and then it stores it into a new byte array. Moreover, here platforms default charset is utilized. Method Definition: byte getBytes() Return Type: It returns a new byte array storing series of bytes. Example #1: // Scala program of getBytes() // method // Creating ob
1 min read
Scala String hashCode() method with example
The hashCode() method is utilized to find the hash code of the stated string. Method Definition: int hashCode() Return Type: It returns an integer hash code of the string given. Example #1: // Scala program of int hashCode() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Applying hashCode method val resul
1 min read
Scala String indexOf() method with example
The indexOf() method is utilized to find the index of the first appearance of the character in the string and the character is present in the method as argument. Method Definition: int indexOf(int ch) Return Type: It returns the index of the character stated in the argument. Example #1: // Scala program of int indexOf() // method // Creating object
1 min read
Scala String indexOf(int ch, int fromIndex) method with example
The indexOf(int ch, int fromIndex) method is same as indexOf() method but here this method starts finding the character from the index we specify. Method Definition: int indexOf(int ch, int fromIndex) Return Type: It returns the index of the character specified in the argument. Example #1: // Scala program of int indexOf() // method // Creating obj
1 min read
Scala String intern() method with example
The intern() method is utilized to check the canonical presentation of the string object. Method Definition: String intern() Return Type: It returns the canonical presentation of the string object. Example: 1# // Scala program of int intern() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Applying intern
1 min read
Scala String lastIndexOf() method with example
The lastIndexOf() method is utilized to return the index of the last appearance of the character we specify in the argument from the stated string. Method Definition: int lastIndexOf(int ch) Return Type: It returns the index of the last appearance of the character in the argument. Example #1: // Scala program of int lastIndexOf() // method // Creat
1 min read
Scala String lastIndexOf(int ch, int fromIndex)() method with example
The lastIndexOf() method is utilized to return the index of the last appearance of the character we specify in the argument from the index we specify for the stated string. Method Definition: int lastIndexOf(int ch, int fromIndex) Return Type: It returns the index of the last appearance of the character in the argument from the index we specify. Ex
1 min read
Article Tags :