Extension Methods
Extension methods add new methods to types you didn’t write, making code read naturally.
On this page · 5 min · Advanced
On this page
- In simple words
- Learning objectives
- Explanation
- Code example
- Step by step
- Real-world use
- Common mistakes
- Best practices
- Remember this
- Practice exercise
- Mini quiz
- Related topics
- My notes
- Reading time
- 5 min
- Difficulty
- Advanced
- Updated
- Oct 30, 2026
In simple words#
An extension method is a phone cover with a built-in stand: you add a feature to the phone without opening it up or changing how it was made.
- extension
- Defines methods for an existing type.
- Receiver
- The value the method is called on.
- Import scope
- Extensions work where they are visible.
Learning objectives#
- Write extension methods
- Group related extensions
- Combine extensions with type classes
- Control visibility with imports
Explanation#
extension (s: String) def isEmail: Boolean = s.contains("@") lets you write "a@b.com".isEmail.
Group several methods: extension (n: Int) { def rupees … ; def lakhs … }.
Extensions can be generic and require type classes: extension [A](a: A)(using Show[A]) def show = ….
Define them in objects and import where needed to avoid clutter.
Code example: Rupee formatting and validation#
object syntax:
extension (amount: Double)
def rupees: String = f"₹$amount%,.2f"
def withGst: Double = amount * 1.18
extension (n: Int)
def lakh: Int = n * 100000
extension (s: String)
def isValidPin: Boolean = s.length == 6 && s.forall(_.isDigit)
import syntax.*
println(1499.0.withGst.rupees)
println(5.lakh)
println("411001".isValidPin)
println("4110".isValidPin)
₹1,768.82 500000 true false
This example is illustrative. Copy or download it and run it in your own environment; the expected output is shown above.
Step-by-step explanation#
- Extensions are grouped in object syntax.
- import syntax.* brings them into scope.
- Calls read like built-in methods.
- Original types are unchanged.
Real-world use case#
Teams create small DSLs: 5.lakh, order.isOverdue, "text".slugify — readable and consistent.
Common mistakes#
Collect them in one object per domain and import explicitly.
Real members win over extensions; choose distinct names.
Best practices#
- Group in objects
- Import explicitly
- Keep them small
- Use for readability, not hidden logic
Remember this#
extension (x: T) def m = …
Import to use.
Adds methods without changing the type.
Practice exercise#
Your task: Add an extension method initials to String ("Asha Verma" → "AV").
Show solution
extension (s: String)
def initials: String = s.split(" ").map(_.head).mkString
Mini quiz#
Extension methods modify the original class definition.
Want more? Practise all Scala MCQs · Scala interview questions
My notes#
Saved in this browser.