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

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)