SlideShare una empresa de Scribd logo
1 de 22
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 !!!

Más contenido relacionado

La actualidad más candente

javascript
javascript javascript
javascript
Kaya Ota
 
Effective Scala: Programming Patterns
Effective Scala: Programming PatternsEffective Scala: Programming Patterns
Effective Scala: Programming Patterns
Vasil Remeniuk
 
Real-World Scala Design Patterns
Real-World Scala Design PatternsReal-World Scala Design Patterns
Real-World Scala Design Patterns
NLJUG
 
Javascript - Tutorial
Javascript - TutorialJavascript - Tutorial
Javascript - Tutorial
adelaticleanu
 

La actualidad más candente (20)

javascript
javascript javascript
javascript
 
Effective Scala: Programming Patterns
Effective Scala: Programming PatternsEffective Scala: Programming Patterns
Effective Scala: Programming Patterns
 
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
 
Rails interview questions
Rails interview questionsRails interview questions
Rails interview questions
 
Javascript Journey
Javascript JourneyJavascript Journey
Javascript Journey
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Real-World Scala Design Patterns
Real-World Scala Design PatternsReal-World Scala Design Patterns
Real-World Scala Design Patterns
 
Chapter 2 java
Chapter 2 javaChapter 2 java
Chapter 2 java
 
Javascript
JavascriptJavascript
Javascript
 
JavaScript operators
JavaScript operatorsJavaScript operators
JavaScript operators
 
Javascript
JavascriptJavascript
Javascript
 
8 introduction to_java_script
8 introduction to_java_script8 introduction to_java_script
8 introduction to_java_script
 
JS - Basics
JS - BasicsJS - Basics
JS - Basics
 
JavaScript - Chapter 5 - Operators
 JavaScript - Chapter 5 - Operators JavaScript - Chapter 5 - Operators
JavaScript - Chapter 5 - Operators
 
From DOT to Dotty
From DOT to DottyFrom DOT to Dotty
From DOT to Dotty
 
Javascript functions
Javascript functionsJavascript functions
Javascript functions
 
Placement and variable 03 (js)
Placement and variable 03 (js)Placement and variable 03 (js)
Placement and variable 03 (js)
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Javascript - Tutorial
Javascript - TutorialJavascript - Tutorial
Javascript - Tutorial
 
Java essentials for hadoop
Java essentials for hadoopJava essentials for hadoop
Java essentials for hadoop
 

Destacado

Destacado (20)

Introduction to ScalaZ
Introduction to ScalaZIntroduction to ScalaZ
Introduction to ScalaZ
 
Functional programming in Javascript
Functional programming in JavascriptFunctional programming in Javascript
Functional programming in Javascript
 
String Interpolation in Scala
String Interpolation in ScalaString Interpolation in Scala
String Interpolation in Scala
 
Introduction to Scala JS
Introduction to Scala JSIntroduction to Scala JS
Introduction to Scala JS
 
Drilling the Async Library
Drilling the Async LibraryDrilling the Async Library
Drilling the Async Library
 
Akka streams
Akka streamsAkka streams
Akka streams
 
Getting Started With AureliaJs
Getting Started With AureliaJsGetting Started With AureliaJs
Getting Started With AureliaJs
 
Realm Mobile Database - An Introduction
Realm Mobile Database - An IntroductionRealm Mobile Database - An Introduction
Realm Mobile Database - An Introduction
 
Mailchimp and Mandrill - The ‘Hominidae’ kingdom
Mailchimp and Mandrill - The ‘Hominidae’ kingdomMailchimp and Mandrill - The ‘Hominidae’ kingdom
Mailchimp and Mandrill - The ‘Hominidae’ kingdom
 
Kanban
KanbanKanban
Kanban
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
 
An Introduction to Quill
An Introduction to QuillAn Introduction to Quill
An Introduction to Quill
 
Introduction to Scala Macros
Introduction to Scala MacrosIntroduction to Scala Macros
Introduction to Scala Macros
 
Mandrill Templates
Mandrill TemplatesMandrill Templates
Mandrill Templates
 
ANTLR4 and its testing
ANTLR4 and its testingANTLR4 and its testing
ANTLR4 and its testing
 
Introduction to Knockout Js
Introduction to Knockout JsIntroduction to Knockout Js
Introduction to Knockout Js
 
Functors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In ScalaFunctors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In Scala
 
Effective way to code in Scala
Effective way to code in ScalaEffective way to code in Scala
Effective way to code in Scala
 
HTML5, CSS, JavaScript Style guide and coding conventions
HTML5, CSS, JavaScript Style guide and coding conventionsHTML5, CSS, JavaScript Style guide and coding conventions
HTML5, CSS, JavaScript Style guide and coding conventions
 
MongoDB: Advance concepts - Replication and Sharding
MongoDB: Advance concepts - Replication and ShardingMongoDB: Advance concepts - Replication and Sharding
MongoDB: Advance concepts - Replication and Sharding
 

Similar a String interpolation

Java căn bản - Chapter9
Java căn bản - Chapter9Java căn bản - Chapter9
Java căn bản - Chapter9
Vince Vo
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
Raj Gupta
 
Scala Language Intro - Inspired by the Love Game
Scala Language Intro - Inspired by the Love GameScala Language Intro - Inspired by the Love Game
Scala Language Intro - Inspired by the Love Game
Antony Stubbs
 

Similar a String interpolation (20)

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
 
Python - Regular Expressions
Python - Regular ExpressionsPython - Regular Expressions
Python - Regular Expressions
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
 
Plunging Into Perl While Avoiding the Deep End (mostly)
Plunging Into Perl While Avoiding the Deep End (mostly)Plunging Into Perl While Avoiding the Deep End (mostly)
Plunging Into Perl While Avoiding the Deep End (mostly)
 
Strings v.1.1
Strings v.1.1Strings v.1.1
Strings v.1.1
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
Bioinformatica 06-10-2011-p2 introduction
Bioinformatica 06-10-2011-p2 introductionBioinformatica 06-10-2011-p2 introduction
Bioinformatica 06-10-2011-p2 introduction
 
Scala Language Intro - Inspired by the Love Game
Scala Language Intro - Inspired by the Love GameScala Language Intro - Inspired by the Love Game
Scala Language Intro - Inspired by the Love Game
 
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...
 
Why Scala?
Why Scala?Why Scala?
Why Scala?
 
Unix commands
Unix commandsUnix commands
Unix commands
 
Adv. python regular expression by Rj
Adv. python regular expression by RjAdv. python regular expression by Rj
Adv. python regular expression by Rj
 
perl course-in-mumbai
 perl course-in-mumbai perl course-in-mumbai
perl course-in-mumbai
 
perl course-in-mumbai
perl course-in-mumbaiperl course-in-mumbai
perl course-in-mumbai
 
Matlab strings
Matlab stringsMatlab strings
Matlab strings
 
core java
 core java core java
core java
 
JavaScript.pptx
JavaScript.pptxJavaScript.pptx
JavaScript.pptx
 
Regular_Expressions.pptx
Regular_Expressions.pptxRegular_Expressions.pptx
Regular_Expressions.pptx
 

Más de Knoldus Inc.

Más de Knoldus Inc. (20)

Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptx
 
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
 

Último

Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
chiefasafspells
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 

Último (20)

%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 

String interpolation

  • 1. String Interpolation SAHIL SAWHNEY Software Consultant KNOLDUS SOFTWARE LLP SAHIL SAWHNEY Software Consultant KNOLDUS SOFTWARE LLP
  • 2. Agenda ● What is string interpolation ● Types of string interpolation ● Exploring each type ● Case study
  • 3. 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’
  • 4. What is interpolation? “To put (words) into a piece of writing or a conversation” -Merriam Webster So what shall string interpolation in Scala mean?
  • 5. 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.
  • 6. 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.
  • 7. 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.
  • 8. ‘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.
  • 9. 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.
  • 10. 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]
  • 11. ‘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.
  • 12. 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.
  • 13. 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]
  • 14. ‘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.
  • 15. 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`
  • 16. 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]
  • 18. 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
  • 19. 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)