
- Scala - Home
- Scala - Overview
- Scala - Features
- Scala - Environment Setup
- Scala - Build Tool (SBT)
- Scala - REPL
- Scala - Dot & Dotty
- Scala - Basic Syntax
- Scala - Hello World Program
- Scala - Identifiers
- Scala - Keywords
- Scala - Comments
- Scala - Code Blocks
- Scala - Semicolon
- Scala - Constructs
- Scala - Expressions
- Scala - Input and Output
- Scala - Optional Braces
- Scala - Underscore (_)
- Data Types and Variables
- Scala - Data Types
- Scala - Type Bounds
- Scala - Context Bound
- Scala - Variances
- Scala - Type Hierarchy
- Scala - Variables
- Scala - Variable Scopes
- Scala - Literals
- Scala - Numeric Types
- Scala - Boolean Types
- Scala - Char Type
- Scala - Unit Types
- Scala - Strings
- Scala - Arrays
- Scala - Null Type
- Scala - Nothing
- Scala - Any Type
- Scala - AnyRef Type
- Scala - Unified Types
- Scala - Dates and Times
- Scala - Ranges
- Scala - Multidimensional Arrays
- Scala - WrappedArray
- Scala - StringBuilder
- Scala - String Interpolation
- Scala - StringContext
- Scala - Type Casting
- Scala var vs val
- Scala Operators
- Scala - Operators
- Scala - Rules for Operators
- Scala - Arithmetic Operators
- Scala - Relational Operators
- Scala - Logical Operators
- Scala - Bitwise Operators
- Scala - Assignment Operators
- Scala - Operators Precedence
- Scala - Symbolic Operators
- Scala - Range Operator
- Scala - String Concatenation Operator
- Scala Conditional Statements
- Scala - IF ELSE
- Scala - IF-ELSE-IF-ELSE Statement
- Scala - Nested IF-ELSE Statement
- Scala Loop Statements
- Scala - Loop Statements
- Scala - while Loop
- Scala - do-while Loop
- Scala - Nested Loops
- Scala - for Loop
- Scala - break Statement
- Scala - yield Keyword
- Scala Classes & Objects
- Scala - Classes & Objects
- Scala - Constructors
- Scala - Auxiliary Constructor
- Scala - Primary Constructor
- Scala - This Keyword
- Scala - Nested Classes
- Scala - Getters and Setters
- Scala - Object Private Fields
- Scala - Singleton Object
- Scala - Companion Objects
- Scala - Creating Executable Programs
- Scala - Stateful Object
- Scala - Enumerations
- Scala - Polymorphism
- Scala - Access Modifiers
- Scala - Apply Method
- Scala - Update Methods
- Scala - UnapplySeq Method
- Scala - Inheritance
- Scala - Extending a Class
- Scala - Method Overloading
- Scala - Method Overriding
- Scala - Generic Classes
- Scala - Generic Functions
- Scala - Superclass Construction
- Scala Methods & Functions
- Scala - Functions
- Scala - Main Methods
- Scala - Functions Call-by-Name
- Scala - Functions with Named Arguments
- Scala - Function with Variable Arguments
- Scala - Recursion Functions
- Scala - Default Parameter Values
- Scala - Functions without Parameters
- Scala - Implicit Parameters
- Scala - Higher-Order Functions
- Scala - Nested Functions
- Scala - Extension Methods
- Scala - Anonymous Functions
- Partially Applied Functions
- Scala - Lazy Val
- Scala - Pure Function
- Scala - Currying Functions
- Scala - Control Abstractions
- Scala - Corecursion
- Scala - Unfold
- Scala - Tail Recursion
- Scala - Infinite Sequences
- Scala - Dynamic Invocation
- Scala - Lambda Expressions
- Scala Collections
- Scala - Collections
- Mutable and Immutable Collections
- Scala - Lists
- Scala - Sets
- Scala - Maps
- Scala - TreeMap
- Scala - SortedMap
- Scala - Tuples
- Scala - Iterators
- Scala - Options
- Scala - Infinite Streams
- Scala - Parallel Collections
- Scala - Algebraic Data Types
- Scala Pattern Matching
- Scala - Pattern Matching
- Scala - Type Patterns
- Scala - Exception Handling
- Scala - Extractors
- Scala - Regular Expressions
- Scala Files I/O
- Scala - Files I/O
- Scala Advanced Concepts
- Scala - Closures
- Scala - Futures
- Scala - Promises
- Scala - Traits
- Scala - Trait Mixins
- Scala - Layered Traits
- Scala - Trait Linearization
- Scala - Sealed Traits
- Scala - Transparent Traits
- Scala - Literal Type Arithmetic
- Scala - Inline keyword
- Scala - Def, Var & Val
- Scala - Dropped Features
- Scala - BDD Testing
Scala - StringContext
StringContext in Scala works with string interpolation. StringContext includeS variables and expressions inside strings easily. It can also create custom ways to insert these variables and manage how these appear within strings. We will discuss StringContext in this post.
Introduction to StringContext
StringContext is a class in the Scala standard library. It creates interpolated strings. It is responsible for parsing and processing string literals that include embedded expressions. You can define custom interpolators which have flexibility and extend the capabilities of string interpolation.
1. Basic Operations
StringContext has various methods and properties that can be used to manipulate and construct strings dynamically. It is the backbone for the predefined interpolators (s, f, and raw) and for the creation of new ones.
Creating a StringContext
StringContext is automatically created when interpolated string is defined.
For example,
val name = "Scala" val context = new StringContext("Hello, ", "!") val result = context.s(name) println(result)
The output will be,
Hello, Scala!
Note that, to get the above output, you need to write the above code, like this:
object Main extends App { val name = "Scala" val context = new StringContext("Hello, ", "!") val result = context.s(name) println(result) }
Static and Dynamic Parts
StringContext splits the interpolated string into static parts and dynamic arguments.
For example,
object Main extends App { val name = "Scala" val context = StringContext("Hello, ", "!") // Accessing static parts val staticParts = context.parts println("Static Parts:") staticParts.foreach(println) // Accessing dynamic arguments val dynamicArgs = "Scala" println("\nDynamic Arguments:") println(dynamicArgs) }
The output will be,
Static Parts: Hello, ! Dynamic Arguments: Scala
2. Custom Interpolators
StringContext in Scala has the ability to define custom string interpolators. It provides specialized string processing capabilities.
Defining a Custom Interpolator
To create a custom interpolator, you need to define implicit class with the apply / unapply method. For example, creating a cap interpolator to capitalize embedded strings:
object Main extends App { implicit class CapInterpolator(val sc: StringContext) extends AnyVal { def cap(args: Any*): String = { val parts = sc.parts.iterator val expressions = args.iterator val sb = new StringBuilder while (parts.hasNext) { sb.append(parts.next()) if (expressions.hasNext) { sb.append(expressions.next().toString.capitalize) } } sb.toString() } } val name = "scala" val hello = "hello" println(cap"$hello, $name") }
The output will be,
Hello, Scala
Using Custom Interpolators
Once defined, custom interpolators can be used in the same way as the built-in ones. For example:
object CustomInterpolators { implicit class CapInterpolator(val sc: StringContext) extends AnyVal { def cap(args: Any*): String = { val parts = sc.parts.iterator val expressions = args.iterator val sb = new StringBuilder(parts.next()) while (parts.hasNext) { sb.append(expressions.next().toString.capitalize) sb.append(parts.next()) } sb.toString() } } } object Main extends App { import CustomInterpolators._ val language = "scala" val website = "tutorialspoint" println(cap"I am learning $language from $website.") }
The output will be,
I am learning Scala from Tutorialspoint.
Advantages of StringContext
- Flexibility − StringContext can create and manage interpolated strings with custom behaviors and processing logic.
- Extensibility − You can have custom interpolators in StringContext that expand string capabilities to meet specific needs.
- Integration − You can integrate the Scala type system. So, it can have custom interpolators for compile-time checks and validations.