SlideShare a Scribd company logo
String Interpolation In Scala

Ruchi Agarwal
Software Consultant
Knoldus Software LLP
Index:
●
●

●

Introduction
String Interpolation in Scala
Usage
●

The s String Interpolator
●

●
●

Using expressions in string literals

The f Interpolator
The raw Interpolator
Introduction:
- String interpolation is the replacement of defined character sequences in the string by values
or variable values.
- Its common in many programming languages which make heavy use of string representations
of data, such as Python, Ruby, PHP, Perl, Scala etc.
- It means to insert a string or replace a variable with its value. It makes string formatting and
specifying contents more intuitive
- Variable interpolation is variable substitution with its value inside a string
- Variable interpolation occurs when the string literal is double-quoted, but not when it is
single-quoted
- The variables are recognized because variables start with a sigil (typically "$")
- Java doesn't support variable interpolation, but it supports more advanced interpolation with a
special formatting function, such as printf, in which the first argument, the format, specifies the
pattern in which the remaining arguments are substituted
Example:
String name = "James";
String output = String.format("Hello %s !", name);
System.out.printf(“Hello %s !”, name);
System.out.format(“Hello %s !”, name);

//string formatting
String Interpolation in Scala:
- Starting in Scala 2.10.0, Scala offers a new mechanism to create strings from data: String
Interpolation
- String interpolation was introduced by SIP-11, which contains all details of the
implementation
- String Interpolation allows users to embed variable references directly in processed string
literals.
Example:
scala> val name = "James"
name: String = James
scala> println(s"Hello, $name !")
Hello, James !
- In the above, the literal s"Hello, $name" is a processed string literal. This means that the
compiler does some additional work to this literal. A processed string literal is denoted by a set
of characters precedding the "
The s String Interpolator:
- Prepending s to any string literal allows the usage of variables directly in the string
Example:
scala> val name = "James"
name: String = James
scala> println(s"Hello, $name !")
Hello, James !
- Here $name is nested inside an s processed string.
- The s interpolator insert the value of the name variable at this location in the string, resulting
in the string Hello, James
- With the s interpolator, any name that is in scope can be used within a string
Using expressions in string literals:
- In addition to putting variables inside strings, we can include expressions ( arbitrary expressions)
inside a string by placing the expression inside curly braces
Example:
scala> println(s"1 + 1 = ${1 + 1}")
1+1=2
- Any arbitrary expression can be embedded in ${}
- Also need to use curly braces when printing object fields.
Example:
scala> case class Student(name: String, score: Int)
defined class Student
scala> val student = Student("James", 95)
student: Student = Student(James,95)
scala> println(s"${student.name} has a score of ${student.score}")
James has a score of 95
- Attempting to print the values of the object fields without wrapping them in curly braces
results in the wrong information being printed out:
// error: this is intentionally wrong
scala> println(s"$student.name has a score of $student.score")
Student(James,95).name has a score of Student(James,95).score
- Because $student.name wasn’t wrapped in curly braces, the wrong information was
printed; in this case, the toString output of the student variable.
The f String Interpolator:
- Prepending f to any string literal allows the creation of simple formatted strings, similar to printf in
other languages. When using the f interpolator, all variable references should be followed by a printfstyle format string, like %d.
Example:
scala> val height = 1.9d
height: Double = 1.9
scala> val name = "James"
name: String = James
scala> f"$name%s is $height%.2f meters tall")
String = James is 1.90 meters tall
- The f interpolator is typesafe. If you try to pass a format string that only works for integers but pass a
double, the compiler will issue an error.
Example:
scala> f"$height%d"
<console>:9: error: type mismatch;
found : Double
required: Int
f"$height%d"
^
- The f interpolator makes use of the string format utilities available from Java. The formats
allowed after the % character are outlined in the Formatter javadoc. If there is no % character after
a variable definition a formatter of %s (String) is assumed.
The raw String Interpolator:
- The raw interpolator is similar to the s interpolator except that it performs “No escaping of literals
within the string”
Example:
scala> s"anb"
res0: String =
a
b
- Here the s string interpolator replaced the characters n with a return character. The raw interpolator
will not do that
Example:
scala> raw"anb"
res1: String = anb
- The raw interpolator is useful when you want to avoid having a sequence of characters like n turn
into a newline character
- In addition to the three default string interpolators, users can define their own
String Interpolation in Scala

More Related Content

ODP
String interpolation
PPTX
4 Expressions and Operators
PPTX
Ruby data types and objects
ODP
Shapeless- Generic programming for Scala
PPTX
Intro to Scala
PPT
Scala Language Intro - Inspired by the Love Game
PPTX
Regular Expressions
PPTX
Fundamental programming structures in java
String interpolation
4 Expressions and Operators
Ruby data types and objects
Shapeless- Generic programming for Scala
Intro to Scala
Scala Language Intro - Inspired by the Love Game
Regular Expressions
Fundamental programming structures in java

What's hot (19)

PDF
2 variables and data types
PDF
Ruby_Basic
ODP
Functors, Applicatives and Monads In Scala
PPT
The ruby programming language
PPTX
Developer’s viewpoint on swift programming language
PPTX
learn Ruby in AMC Square learning
PPTX
Polymorphism
PPT
Java findamentals2
PDF
Write codeforhumans
PDF
Functional programming with F#
PPTX
Quick Scala
PDF
Demystifying Shapeless
PPTX
Python Training in Bangalore | Python Introduction Session | Learnbay
PDF
Javascript Journey
PPTX
Ruby object model - Understanding of object play role for ruby
PPTX
Operators in java
2 variables and data types
Ruby_Basic
Functors, Applicatives and Monads In Scala
The ruby programming language
Developer’s viewpoint on swift programming language
learn Ruby in AMC Square learning
Polymorphism
Java findamentals2
Write codeforhumans
Functional programming with F#
Quick Scala
Demystifying Shapeless
Python Training in Bangalore | Python Introduction Session | Learnbay
Javascript Journey
Ruby object model - Understanding of object play role for ruby
Operators in java
Ad

Similar to String Interpolation in Scala (20)

PPTX
The Literals and Variables Concept in Python.pptx
PDF
Python regular expressions
PPT
Chapter 9 - Characters and Strings
PPT
Java căn bản - Chapter9
PDF
newperl5
PDF
newperl5
PPTX
Strings,patterns and regular expressions in perl
PPTX
Unit 1-strings,patterns and regular expressions
PDF
RegexCat
PPT
Intro To Scala
PDF
python_strings.pdf
PPT
Php, mysqlpart2
PPTX
JavaScript.pptx
PDF
Python syntax
PDF
3 character strings and formatted input output
ODP
PHP Web Programming
PPTX
Python_Unit_III.pptx
PPTX
Scala syntax analysis
DOCX
Python - Regular Expressions
PDF
Perl_Part1
The Literals and Variables Concept in Python.pptx
Python regular expressions
Chapter 9 - Characters and Strings
Java căn bản - Chapter9
newperl5
newperl5
Strings,patterns and regular expressions in perl
Unit 1-strings,patterns and regular expressions
RegexCat
Intro To Scala
python_strings.pdf
Php, mysqlpart2
JavaScript.pptx
Python syntax
3 character strings and formatted input output
PHP Web Programming
Python_Unit_III.pptx
Scala syntax analysis
Python - Regular Expressions
Perl_Part1
Ad

More from Knoldus Inc. (20)

PPTX
Angular Hydration Presentation (FrontEnd)
PPTX
Optimizing Test Execution: Heuristic Algorithm for Self-Healing
PPTX
Self-Healing Test Automation Framework - Healenium
PPTX
Kanban Metrics Presentation (Project Management)
PPTX
Java 17 features and implementation.pptx
PPTX
Chaos Mesh Introducing Chaos in Kubernetes
PPTX
GraalVM - A Step Ahead of JVM Presentation
PPTX
Nomad by HashiCorp Presentation (DevOps)
PPTX
Nomad by HashiCorp Presentation (DevOps)
PPTX
DAPR - Distributed Application Runtime Presentation
PPTX
Introduction to Azure Virtual WAN Presentation
PPTX
Introduction to Argo Rollouts Presentation
PPTX
Intro to Azure Container App Presentation
PPTX
Insights Unveiled Test Reporting and Observability Excellence
PPTX
Introduction to Splunk Presentation (DevOps)
PPTX
Code Camp - Data Profiling and Quality Analysis Framework
PPTX
AWS: Messaging Services in AWS Presentation
PPTX
Amazon Cognito: A Primer on Authentication and Authorization
PPTX
ZIO Http A Functional Approach to Scalable and Type-Safe Web Development
PPTX
Managing State & HTTP Requests In Ionic.
Angular Hydration Presentation (FrontEnd)
Optimizing Test Execution: Heuristic Algorithm for Self-Healing
Self-Healing Test Automation Framework - Healenium
Kanban Metrics Presentation (Project Management)
Java 17 features and implementation.pptx
Chaos Mesh Introducing Chaos in Kubernetes
GraalVM - A Step Ahead of JVM Presentation
Nomad by HashiCorp Presentation (DevOps)
Nomad by HashiCorp Presentation (DevOps)
DAPR - Distributed Application Runtime Presentation
Introduction to Azure Virtual WAN Presentation
Introduction to Argo Rollouts Presentation
Intro to Azure Container App Presentation
Insights Unveiled Test Reporting and Observability Excellence
Introduction to Splunk Presentation (DevOps)
Code Camp - Data Profiling and Quality Analysis Framework
AWS: Messaging Services in AWS Presentation
Amazon Cognito: A Primer on Authentication and Authorization
ZIO Http A Functional Approach to Scalable and Type-Safe Web Development
Managing State & HTTP Requests In Ionic.

Recently uploaded (20)

PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
Spectroscopy.pptx food analysis technology
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Approach and Philosophy of On baking technology
PDF
cuic standard and advanced reporting.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
Big Data Technologies - Introduction.pptx
Digital-Transformation-Roadmap-for-Companies.pptx
Spectroscopy.pptx food analysis technology
Reach Out and Touch Someone: Haptics and Empathic Computing
gpt5_lecture_notes_comprehensive_20250812015547.pdf
20250228 LYD VKU AI Blended-Learning.pptx
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Approach and Philosophy of On baking technology
cuic standard and advanced reporting.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
Spectral efficient network and resource selection model in 5G networks
NewMind AI Weekly Chronicles - August'25-Week II
Programs and apps: productivity, graphics, security and other tools
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Review of recent advances in non-invasive hemoglobin estimation
Diabetes mellitus diagnosis method based random forest with bat algorithm
A comparative analysis of optical character recognition models for extracting...
Network Security Unit 5.pdf for BCA BBA.
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Big Data Technologies - Introduction.pptx

String Interpolation in Scala

  • 1. String Interpolation In Scala Ruchi Agarwal Software Consultant Knoldus Software LLP
  • 2. Index: ● ● ● Introduction String Interpolation in Scala Usage ● The s String Interpolator ● ● ● Using expressions in string literals The f Interpolator The raw Interpolator
  • 3. Introduction: - String interpolation is the replacement of defined character sequences in the string by values or variable values. - Its common in many programming languages which make heavy use of string representations of data, such as Python, Ruby, PHP, Perl, Scala etc. - It means to insert a string or replace a variable with its value. It makes string formatting and specifying contents more intuitive - Variable interpolation is variable substitution with its value inside a string - Variable interpolation occurs when the string literal is double-quoted, but not when it is single-quoted - The variables are recognized because variables start with a sigil (typically "$") - Java doesn't support variable interpolation, but it supports more advanced interpolation with a special formatting function, such as printf, in which the first argument, the format, specifies the pattern in which the remaining arguments are substituted
  • 4. Example: String name = "James"; String output = String.format("Hello %s !", name); System.out.printf(“Hello %s !”, name); System.out.format(“Hello %s !”, name); //string formatting
  • 5. String Interpolation in Scala: - Starting in Scala 2.10.0, Scala offers a new mechanism to create strings from data: String Interpolation - String interpolation was introduced by SIP-11, which contains all details of the implementation - String Interpolation allows users to embed variable references directly in processed string literals. Example: scala> val name = "James" name: String = James scala> println(s"Hello, $name !") Hello, James ! - In the above, the literal s"Hello, $name" is a processed string literal. This means that the compiler does some additional work to this literal. A processed string literal is denoted by a set of characters precedding the "
  • 6. The s String Interpolator: - Prepending s to any string literal allows the usage of variables directly in the string Example: scala> val name = "James" name: String = James scala> println(s"Hello, $name !") Hello, James ! - Here $name is nested inside an s processed string. - The s interpolator insert the value of the name variable at this location in the string, resulting in the string Hello, James - With the s interpolator, any name that is in scope can be used within a string
  • 7. Using expressions in string literals: - In addition to putting variables inside strings, we can include expressions ( arbitrary expressions) inside a string by placing the expression inside curly braces Example: scala> println(s"1 + 1 = ${1 + 1}") 1+1=2 - Any arbitrary expression can be embedded in ${} - Also need to use curly braces when printing object fields. Example: scala> case class Student(name: String, score: Int) defined class Student scala> val student = Student("James", 95) student: Student = Student(James,95) scala> println(s"${student.name} has a score of ${student.score}") James has a score of 95
  • 8. - Attempting to print the values of the object fields without wrapping them in curly braces results in the wrong information being printed out: // error: this is intentionally wrong scala> println(s"$student.name has a score of $student.score") Student(James,95).name has a score of Student(James,95).score - Because $student.name wasn’t wrapped in curly braces, the wrong information was printed; in this case, the toString output of the student variable.
  • 9. The f String Interpolator: - Prepending f to any string literal allows the creation of simple formatted strings, similar to printf in other languages. When using the f interpolator, all variable references should be followed by a printfstyle format string, like %d. Example: scala> val height = 1.9d height: Double = 1.9 scala> val name = "James" name: String = James scala> f"$name%s is $height%.2f meters tall") String = James is 1.90 meters tall - The f interpolator is typesafe. If you try to pass a format string that only works for integers but pass a double, the compiler will issue an error.
  • 10. Example: scala> f"$height%d" <console>:9: error: type mismatch; found : Double required: Int f"$height%d" ^ - The f interpolator makes use of the string format utilities available from Java. The formats allowed after the % character are outlined in the Formatter javadoc. If there is no % character after a variable definition a formatter of %s (String) is assumed.
  • 11. The raw String Interpolator: - The raw interpolator is similar to the s interpolator except that it performs “No escaping of literals within the string” Example: scala> s"anb" res0: String = a b - Here the s string interpolator replaced the characters n with a return character. The raw interpolator will not do that Example: scala> raw"anb" res1: String = anb - The raw interpolator is useful when you want to avoid having a sequence of characters like n turn into a newline character - In addition to the three default string interpolators, users can define their own