SlideShare a Scribd company logo
1 of 12
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

What's hot

2 variables and data types
2   variables and data types2   variables and data types
2 variables and data typesTuan Ngo
 
Functors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In ScalaFunctors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In ScalaKnoldus Inc.
 
The ruby programming language
The ruby programming languageThe ruby programming language
The ruby programming languagepraveen0202
 
Developer’s viewpoint on swift programming language
Developer’s viewpoint on swift programming languageDeveloper’s viewpoint on swift programming language
Developer’s viewpoint on swift programming languageAzilen Technologies Pvt. Ltd.
 
learn Ruby in AMC Square learning
learn Ruby in AMC Square learninglearn Ruby in AMC Square learning
learn Ruby in AMC Square learningASIT Education
 
Java findamentals2
Java findamentals2Java findamentals2
Java findamentals2Todor Kolev
 
Write codeforhumans
Write codeforhumansWrite codeforhumans
Write codeforhumansNarendran R
 
Functional programming with F#
Functional programming with F#Functional programming with F#
Functional programming with F#Remik Koczapski
 
Demystifying Shapeless
Demystifying Shapeless Demystifying Shapeless
Demystifying Shapeless Jared Roesch
 
Python Training in Bangalore | Python Introduction Session | Learnbay
Python Training in Bangalore |  Python Introduction Session | LearnbayPython Training in Bangalore |  Python Introduction Session | Learnbay
Python Training in Bangalore | Python Introduction Session | LearnbayLearnbayin
 
Javascript Journey
Javascript JourneyJavascript Journey
Javascript JourneyWanqiang Ji
 
Ruby object model - Understanding of object play role for ruby
Ruby object model - Understanding of object play role for rubyRuby object model - Understanding of object play role for ruby
Ruby object model - Understanding of object play role for rubyTushar Pal
 

What's hot (19)

2 variables and data types
2   variables and data types2   variables and data types
2 variables and data types
 
Ruby_Basic
Ruby_BasicRuby_Basic
Ruby_Basic
 
Functors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In ScalaFunctors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In Scala
 
Text processing by Rj
Text processing by RjText processing by Rj
Text processing by Rj
 
The ruby programming language
The ruby programming languageThe ruby programming language
The ruby programming language
 
Developer’s viewpoint on swift programming language
Developer’s viewpoint on swift programming languageDeveloper’s viewpoint on swift programming language
Developer’s viewpoint on swift programming language
 
learn Ruby in AMC Square learning
learn Ruby in AMC Square learninglearn Ruby in AMC Square learning
learn Ruby in AMC Square learning
 
PHP
PHPPHP
PHP
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Ruby
RubyRuby
Ruby
 
Java findamentals2
Java findamentals2Java findamentals2
Java findamentals2
 
Write codeforhumans
Write codeforhumansWrite codeforhumans
Write codeforhumans
 
Functional programming with F#
Functional programming with F#Functional programming with F#
Functional programming with F#
 
Quick Scala
Quick ScalaQuick Scala
Quick Scala
 
Demystifying Shapeless
Demystifying Shapeless Demystifying Shapeless
Demystifying Shapeless
 
Python Training in Bangalore | Python Introduction Session | Learnbay
Python Training in Bangalore |  Python Introduction Session | LearnbayPython Training in Bangalore |  Python Introduction Session | Learnbay
Python Training in Bangalore | Python Introduction Session | Learnbay
 
Javascript Journey
Javascript JourneyJavascript Journey
Javascript Journey
 
Ruby object model - Understanding of object play role for ruby
Ruby object model - Understanding of object play role for rubyRuby object model - Understanding of object play role for ruby
Ruby object model - Understanding of object play role for ruby
 
Operators in java
Operators in javaOperators in java
Operators in java
 

Similar to String Interpolation in Scala

Python regular expressions
Python regular expressionsPython regular expressions
Python regular expressionsKrishna Nanda
 
Chapter 9 - Characters and Strings
Chapter 9 - Characters and StringsChapter 9 - Characters and Strings
Chapter 9 - Characters and StringsEduardo Bergavera
 
Java căn bản - Chapter9
Java căn bản - Chapter9Java căn bản - Chapter9
Java căn bản - Chapter9Vince Vo
 
Strings,patterns and regular expressions in perl
Strings,patterns and regular expressions in perlStrings,patterns and regular expressions in perl
Strings,patterns and regular expressions in perlsana mateen
 
Unit 1-strings,patterns and regular expressions
Unit 1-strings,patterns and regular expressionsUnit 1-strings,patterns and regular expressions
Unit 1-strings,patterns and regular expressionssana mateen
 
Intro To Scala
Intro To ScalaIntro To Scala
Intro To Scalachambeda
 
3 character strings and formatted input output
3  character strings and formatted input output3  character strings and formatted input output
3 character strings and formatted input outputMomenMostafa
 
Python_Unit_III.pptx
Python_Unit_III.pptxPython_Unit_III.pptx
Python_Unit_III.pptxssuserc755f1
 
Python - Regular Expressions
Python - Regular ExpressionsPython - Regular Expressions
Python - Regular ExpressionsMukesh Tekwani
 
International Journal of Engineering Research and Development (IJERD)
International Journal of Engineering Research and Development (IJERD)International Journal of Engineering Research and Development (IJERD)
International Journal of Engineering Research and Development (IJERD)IJERD Editor
 

Similar to String Interpolation in Scala (20)

Python regular expressions
Python regular expressionsPython regular expressions
Python regular expressions
 
Chapter 9 - Characters and Strings
Chapter 9 - Characters and StringsChapter 9 - Characters and Strings
Chapter 9 - Characters and Strings
 
Java căn bản - Chapter9
Java căn bản - Chapter9Java căn bản - Chapter9
Java căn bản - Chapter9
 
newperl5
newperl5newperl5
newperl5
 
newperl5
newperl5newperl5
newperl5
 
Strings,patterns and regular expressions in perl
Strings,patterns and regular expressions in perlStrings,patterns and regular expressions in perl
Strings,patterns and regular expressions in perl
 
Unit 1-strings,patterns and regular expressions
Unit 1-strings,patterns and regular expressionsUnit 1-strings,patterns and regular expressions
Unit 1-strings,patterns and regular expressions
 
RegexCat
RegexCatRegexCat
RegexCat
 
Intro To Scala
Intro To ScalaIntro To Scala
Intro To Scala
 
python_strings.pdf
python_strings.pdfpython_strings.pdf
python_strings.pdf
 
Php, mysqlpart2
Php, mysqlpart2Php, mysqlpart2
Php, mysqlpart2
 
JavaScript.pptx
JavaScript.pptxJavaScript.pptx
JavaScript.pptx
 
Python syntax
Python syntaxPython syntax
Python syntax
 
3 character strings and formatted input output
3  character strings and formatted input output3  character strings and formatted input output
3 character strings and formatted input output
 
PHP Web Programming
PHP Web ProgrammingPHP Web Programming
PHP Web Programming
 
Python_Unit_III.pptx
Python_Unit_III.pptxPython_Unit_III.pptx
Python_Unit_III.pptx
 
Scala syntax analysis
Scala syntax analysisScala syntax analysis
Scala syntax analysis
 
Python - Regular Expressions
Python - Regular ExpressionsPython - Regular Expressions
Python - Regular Expressions
 
Perl_Part1
Perl_Part1Perl_Part1
Perl_Part1
 
International Journal of Engineering Research and Development (IJERD)
International Journal of Engineering Research and Development (IJERD)International Journal of Engineering Research and Development (IJERD)
International Journal of Engineering Research and Development (IJERD)
 

More from Knoldus Inc.

Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingKnoldus Inc.
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionKnoldus Inc.
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxKnoldus Inc.
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptxKnoldus Inc.
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfKnoldus Inc.
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxKnoldus Inc.
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingKnoldus Inc.
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesKnoldus Inc.
 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxKnoldus Inc.
 
Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxKnoldus Inc.
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxKnoldus Inc.
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxKnoldus Inc.
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxKnoldus Inc.
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationKnoldus Inc.
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationKnoldus Inc.
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIsKnoldus Inc.
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II PresentationKnoldus Inc.
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAKnoldus Inc.
 
Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Knoldus Inc.
 

More from Knoldus Inc. (20)

Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On Introduction
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptx
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptx
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdf
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptx
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable Testing
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose Kubernetes
 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptx
 
Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptx
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptx
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptx
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptx
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake Presentation
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics Presentation
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIs
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II Presentation
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRA
 
Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)
 

Recently uploaded

A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 

Recently uploaded (20)

A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 

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