SlideShare a Scribd company logo
String Interpolation
SAHIL SAWHNEY
Software Consultant
KNOLDUS SOFTWARE LLP
SAHIL SAWHNEY
Software Consultant
KNOLDUS SOFTWARE LLP
Agenda
● What is string interpolation
● Types of string interpolation
● Exploring each type
● Case study
What are we going to learn?
➔ What we want to do here?
Compose a string by concatenating values (variables and
constants) in it.
➔ What we are actually doing here?
Inducing the ‘Yuck Factor’
What is interpolation?
“To put (words) into a piece of writing or a
conversation”
-Merriam Webster
So what shall string interpolation in Scala mean?
String Interpolation in scala
➔ It is a mechanism that enable us to
sew/embed/bind WORDS in between a
processed/unprocessed string literal.
➔ Here by processed string literal we mean
processing of meta-characters like escape
sequences(n, t, r etc.) in the string.
What these ‘WORDS’ are?
➔Variables and constants
var a =5; val b=55;
➔Result yielding expressions
Match case
If-else
Try-catch
You name it.
The three mess saviors
➔
The ‘s’ interpolator (Simple string interpolator).
➔
The ‘raw’ interpolator (Raw string interpolator).
➔
The ‘f’ interpolator (Formatted string interpolator).
Powered by - ‘StringContext’ class.
‘s’ interpolator
➔ To use this interpolator just prepend the string
with an ‘s’ and put a ‘$’ sign before the values
to be embedded(‘${}’ for the expression).
CAUTION → Just take care there are no
spaces between the ‘$’ and the variable.
What exactly ‘s’ is?
➔ ‘s’ is actually a method of ‘StringContext’ class
with the following signature :-
def s(args: Any*): String =
standardInterpolator(treatEscapes, args)
‘args’ are the arguments to be inserted into resulting string.
‘treatescape’ is the partial function that process the string by
applying escape sequence if any.
Knowing the internals
println(s"$name is $age years old and earns ₹ $salary")
println(new StringContext(""," is ", " years old and earns
","").₹ s(name,age,salary))
parts.length == args.length + 1 (Or IllegalArgumentException)
(Compile Time Reflection)
‘Parts’ of type Seq[String]‘Args’ of type Seq[Any]
‘raw’ interpolator
➔ It is similar to ‘s’ interpolator except for one
difference i.e. it do not process the string.
➔ It just embed the value in a raw (unprocessed)
string literal.
I think we know whats ‘raw’.
➔ Like ‘s’, ‘raw’ is also a method of StringContext
class with following signature :-
def raw(args: Any*): String =
standardInterpolator(identity, args)
➔ ‘args’ are the arguments to be inserted into resulting string
➔ ‘identity’ is a method in ‘Predef.scala’ that returns the same
value what it gets as a parameter.
Knowing the internals
println(raw"$name t is $age years old n”)
println(new StringContext(""," t is ", " years old n","")
.raw(name,age))
parts.length == args.length + 1 (Or IllegalArgumentException)
(Compile Time Reflection)
‘Parts’ of type Seq[String]‘Args’ of type Seq[Any]
‘f’ interpolator
➔ It is based on the printf method used in java and
is used to format the string.
➔ It also process the string before embedding the
values.
➔ All values should be immediately followed by a
printf-style format string.
➔ The f interpolator is type-safe.
➔ If no format is specified, String(%s) is considered
to be the default format.
We definitely know what ‘f’ is
➔ Yes, it is also a method of StringContext class
but with a twist :-
def f[A >: Any](args: A*): String = macro ???
Its implementation is hardwired to →
`scala.tools.reflect.MacroImplementations.macro_StringI
nterpolation_f`
Knowing the internals
println(f"$name t earns $salary%3.2f at $hour%02d n”)
println(new StringContext(""," t earns ", "%3.2f at
","%02d n") .f(name,salary,hour))
parts.length == args.length + 1 (Or corresponding error message)
(Compile Time Reflection)
‘Parts’ of type List[Tree]‘Args’ of type List[Tree]
Demonstration →
https://blog.knoldus.com/2016/07/28/customi
zing-string-interpolation-an-example
To be noted
When do we need an implicit class?
When we need to implement extension methods for an
existing class. Example :-
class MyInt(value:Int){
def kamehameha:Int={value * 10000000000}
}
5.kamehameha → new MyInt(5).kamehameha
The flow
write”$name is $age years oldnand earns $salary”₹
new StringContext(“”, ” is “,” years oldnand earns ₹
“,””).write(name, age,salary)
new WriteScore(new StringContext(“”, ” is “,” years
oldnand earns “,””).write(name, age,salary))₹
(Compile Time)
(Rewriting implicit class)
References
http://docs.scala-lang.org/overviews/core/string-interpo
http://www.scala-lang.org/api/current/index.html#scala.
http://alvinalexander.com/programming/printf-format-ch
http://docs.scala-lang.org/overviews/core/string-interpo
http://www.scala-lang.org/api/current/index.html#scala.
http://alvinalexander.com/programming/printf-format-ch
Any Questions?
Arigato Gozaimasu !!!

More Related Content

ODP
Shapeless- Generic programming for Scala
PPTX
Intro to Scala
PPTX
Advanced Javascript
ODP
Getting started with typescript and angular 2
PPTX
Introduction to Scala
PDF
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
PPTX
Function-and-prototype defined classes in JavaScript
PDF
Swift Tutorial Part 1. The Complete Guide For Swift Programming Language
Shapeless- Generic programming for Scala
Intro to Scala
Advanced Javascript
Getting started with typescript and angular 2
Introduction to Scala
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
Function-and-prototype defined classes in JavaScript
Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

What's hot (20)

PPTX
javascript
PDF
Effective Scala: Programming Patterns
PPTX
Developer’s viewpoint on swift programming language
DOC
Rails interview questions
PDF
Javascript Journey
PPTX
Introduction to JavaScript
PDF
Real-World Scala Design Patterns
PPTX
Chapter 2 java
PPT
Javascript
PPTX
JavaScript operators
PDF
Javascript
PDF
8 introduction to_java_script
PPTX
JS - Basics
PDF
JavaScript - Chapter 5 - Operators
PDF
From DOT to Dotty
PPTX
Javascript functions
PPTX
Placement and variable 03 (js)
PPT
Introduction to Javascript
PDF
Javascript - Tutorial
PDF
Java essentials for hadoop
javascript
Effective Scala: Programming Patterns
Developer’s viewpoint on swift programming language
Rails interview questions
Javascript Journey
Introduction to JavaScript
Real-World Scala Design Patterns
Chapter 2 java
Javascript
JavaScript operators
Javascript
8 introduction to_java_script
JS - Basics
JavaScript - Chapter 5 - Operators
From DOT to Dotty
Javascript functions
Placement and variable 03 (js)
Introduction to Javascript
Javascript - Tutorial
Java essentials for hadoop
Ad

Viewers also liked (20)

ODP
Introduction to ScalaZ
ODP
Functional programming in Javascript
ODP
String Interpolation in Scala
ODP
Introduction to Scala JS
ODP
Drilling the Async Library
ODP
Akka streams
ODP
Getting Started With AureliaJs
ODP
Realm Mobile Database - An Introduction
ODP
Mailchimp and Mandrill - The ‘Hominidae’ kingdom
PDF
Kanban
ODP
Introduction to Java 8
ODP
An Introduction to Quill
ODP
Introduction to Scala Macros
ODP
Mandrill Templates
ODP
ANTLR4 and its testing
ODP
Introduction to Knockout Js
ODP
Functors, Applicatives and Monads In Scala
ODP
Effective way to code in Scala
ODP
HTML5, CSS, JavaScript Style guide and coding conventions
ODP
MongoDB: Advance concepts - Replication and Sharding
Introduction to ScalaZ
Functional programming in Javascript
String Interpolation in Scala
Introduction to Scala JS
Drilling the Async Library
Akka streams
Getting Started With AureliaJs
Realm Mobile Database - An Introduction
Mailchimp and Mandrill - The ‘Hominidae’ kingdom
Kanban
Introduction to Java 8
An Introduction to Quill
Introduction to Scala Macros
Mandrill Templates
ANTLR4 and its testing
Introduction to Knockout Js
Functors, Applicatives and Monads In Scala
Effective way to code in Scala
HTML5, CSS, JavaScript Style guide and coding conventions
MongoDB: Advance concepts - Replication and Sharding
Ad

Similar to String interpolation (20)

PDF
Scala Turkiye 2013-02-07 Sunumu
PDF
Python Lecture Slides topic strings handling
PPTX
Python String Revisited.pptx
PDF
Strings in Python
PDF
All About ... Functions
PDF
python_strings.pdf
PPTX
Lexture about strings, all examples and theoretical part is included
PPTX
varthini python .pptx
PDF
From Python to Scala
PDF
Strings brief introduction in python.pdf
PPTX
ecFDkQifGYWkHLXQ395.pptxbbbbngvbngrrghxcvvb
PPT
Compiler design lessons notes from Semester
PPT
Python workshop intro_string (1)
PPTX
Chapter 11 Strings and methods [Autosaved].pptx
PDF
Python data handling
PPTX
Python Programming-UNIT-II - Strings.pptx
PPTX
Unit-IV Strings.pptx
PPTX
Module 1 - Programming Fundamentals.pptx
PDF
Implicit conversion and parameters
Scala Turkiye 2013-02-07 Sunumu
Python Lecture Slides topic strings handling
Python String Revisited.pptx
Strings in Python
All About ... Functions
python_strings.pdf
Lexture about strings, all examples and theoretical part is included
varthini python .pptx
From Python to Scala
Strings brief introduction in python.pdf
ecFDkQifGYWkHLXQ395.pptxbbbbngvbngrrghxcvvb
Compiler design lessons notes from Semester
Python workshop intro_string (1)
Chapter 11 Strings and methods [Autosaved].pptx
Python data handling
Python Programming-UNIT-II - Strings.pptx
Unit-IV Strings.pptx
Module 1 - Programming Fundamentals.pptx
Implicit conversion and parameters

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)

PDF
Softaken Excel to vCard Converter Software.pdf
PDF
System and Network Administraation Chapter 3
PDF
AI in Product Development-omnex systems
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PPTX
Odoo POS Development Services by CandidRoot Solutions
PDF
System and Network Administration Chapter 2
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PPTX
ai tools demonstartion for schools and inter college
PPTX
L1 - Introduction to python Backend.pptx
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PPTX
Introduction to Artificial Intelligence
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PDF
How Creative Agencies Leverage Project Management Software.pdf
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PPT
Introduction Database Management System for Course Database
PPTX
Online Work Permit System for Fast Permit Processing
Softaken Excel to vCard Converter Software.pdf
System and Network Administraation Chapter 3
AI in Product Development-omnex systems
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Odoo POS Development Services by CandidRoot Solutions
System and Network Administration Chapter 2
Design an Analysis of Algorithms II-SECS-1021-03
ai tools demonstartion for schools and inter college
L1 - Introduction to python Backend.pptx
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
Introduction to Artificial Intelligence
Design an Analysis of Algorithms I-SECS-1021-03
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Navsoft: AI-Powered Business Solutions & Custom Software Development
How Creative Agencies Leverage Project Management Software.pdf
Wondershare Filmora 15 Crack With Activation Key [2025
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Introduction Database Management System for Course Database
Online Work Permit System for Fast Permit Processing

String interpolation