Scala
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Object-Oriented Scala
-
Section 4: Functional Scala
-
Section 5: Collections in Depth
-
Section 6: Type System
-
Section 7: Concurrency and Ecosystem
-
Section 8: Practical Projects
-
Section 9: Interview Practice
-
Section 10: Data Structures and Algorithms in Scala
-
Section 11: More Practice Exercises
-
Section 12: Advanced Functional Patterns
-
Section 13: More Ecosystem
-
Section 14: Scala Collections Library Deep Dive
-
Section 15: Scala Standard Library Deep Dive
-
Section 16: Akka Ecosystem Deep Dive
-
Section 17: Cats and Cats Effect Deep Dive
-
Section 18: Play Framework Deep Dive
-
Section 19: Apache Spark with Scala Deep Dive
-
Section 20: Scala Build Tools Deep Dive
-
Section 21: Scala 3 Specific Features
-
90: Union and Intersection Types
-
Section 22: Scala Testing Deep Dive
-
Section 23: Functional Domain Modeling
-
Section 24: More Data Structures and Algorithms in Scala
-
Section 25: Scala for Data Engineering
-
Section 26: More Practical Projects
-
Section 27: More Interview and Review
-
Section 28: ZIO Ecosystem Deep Dive
-
Section 29: Scala for Machine Learning
-
Section 30: Scala Microservices Architecture
-
Section 31: Scala Type System Deep Dive
-
Section 32: More Practice and Drills
-
Section 33: Scala Performance Deep Dive
-
Section 34: Scala Ecosystem Tooling
-
Section 35: Scala for Reactive Systems
-
Section 36: More Real-World Case Studies
-
Section 37: Scala for Financial Systems
-
Section 38: Scala GraphQL and gRPC
-
Section 39: More Final Projects
-
Section 40: More Interview and Final Review
-
Section 41: Scala for Streaming Data
-
Section 42: Scala Security Practices
-
Section 43: More Language Deep Dive
-
Section 44: Scala Command-Line Tools
-
Section 45: Scala Documentation and Style
-
Section 46: Scala Dependency Management
-
Section 47: More Practical Backend Patterns
-
Section 48: Scala for Event-Driven Architecture
-
Section 49: More Practice Drills Round 2
-
Section 50: Scala Compiler Deep Dive
-
Section 51: Scala for Web Frontends
-
Section 52: More Data Engineering Practice
-
Section 53: Scala Observability
-
Section 54: More Advanced Practice Projects
-
Section 55: Scala for Legacy Java Integration
-
Section 56: More Testing Practice
-
Section 57: Final Mastery Review
-
Section 58: Scala History and Ecosystem Context
-
Section 59: More Concurrency Patterns
-
Section 60: Scala for Configuration Management
-
Section 61: More Domain Modeling Practice
89: Extension Methods in Scala 3
You’ve probably run into this situation a dozen times: you're using a class from a third-party library—something like a PaymentTransaction object from a Stripe or PayPal SDK—and you realize it's missing one simple, helpful method. Maybe you need a isHighValue check or a toAuditString formatter. Since you don't own the source code for that library, you can't just open the file and add the method yourself.
The Utility Class Trap
The traditional "Java-style" way to handle this is to create a utility class. You've seen it everywhere: PaymentUtils, StringUtils, DateHelper. It looks something like this:
case class PaymentTransaction(id: String, amount: Double, currency: String)
object PaymentUtils {
def isHighValue(p: PaymentTransaction): Boolean = p.amount > 1000.0
def formatForLog(p: PaymentTransaction): String = s"[${p.id}] ${p.amount} ${p.currency}"
}
// Usage:
val tx = PaymentTransaction("tx_123", 1500.0, "USD")
if (PaymentUtils.isHighValue(tx)) {
println(PaymentUtils.formatForLog(tx))
}
Now, this works, but it's clunky. I hate writing this because it breaks the natural flow of the logic. Instead of asking the object about its own properties (tx.isHighValue), you're passing the object into a separate machine to get an answer. It also ruins discoverability. When you're typing tx. in your IDE, the autocomplete won't show you isHighValue because that method doesn't actually belong to the transaction; it lives in some random utility object you have to remember exists.
Bringing the Logic to the Data
This is where extension methods in Scala 3 come in. They let us "attach" new methods to an existing type without actually modifying that type's source code. It's purely syntactic sugar at the compiler level, but it makes the API feel like it was designed exactly the way you wanted it from the start.
Here is how I would rewrite that utility logic using an extension block:
case class PaymentTransaction(id: String, amount: Double, currency: String)
extension (p: PaymentTransaction) {
def isHighValue: Boolean = p.amount > 1000.0
def formatForLog: String = s"[${p.id}] ${p.amount} ${p.currency}"
}
// Usage:
val tx = PaymentTransaction("tx_123", 1500.0, "USD")
if (tx.isHighValue) {
println(tx.formatForLog)
}
Notice the difference in the call site. tx.isHighValue reads like a property of the transaction. It's cleaner, it's more intuitive, and most importantly, it shows up in your IDE's autocomplete. You've effectively extended the interface of a class you don't control.
The Cost of the Magic
You might be wondering if we're actually modifying the class at runtime. We aren't. If you look at the bytecode, the Scala compiler is just rewriting tx.isHighValue back into PaymentUtils.isHighValue(tx). It's a compile-time transformation.
There are two things you need to keep in mind here. First, extension methods are scoped. If you define your extension in a separate file, you have to import it to use it. I usually put my extensions in a DomainExtensions or Extensions object to keep things organized, and then I import them specifically where the business logic lives.
Second, extension methods cannot override existing methods. If PaymentTransaction already had a method called isHighValue, the original method always wins. The compiler won't even let you attempt to "shadow" a real member method. This prevents a whole class of bugs where you might accidentally break the core behavior of a library by adding your own version of a method.
📋 Practical Task
Implementing a Currency Formatter for External Transaction Data
You are working with a legacy Invoice class that you cannot modify. You need to add two pieces of functionality to it to help with a reporting dashboard: a method to determine if the invoice is overdue (based on a daysPending field) and a method to format the total amount with its currency symbol.
Requirements:
- Create a case class
Invoice(id: String, amount: Double, currency: String, daysPending: Int). - Define an extension for
Invoicethat adds:isOverdue: ReturnstrueifdaysPendingis greater than 30.formattedAmount: Returns a string like"$100.00"or"€50.00"based on the currency string (assume "USD" maps to "$" and "EUR" maps to "€").
- In your main code, instantiate an
Invoiceand print the results of these two new methods.
There are no comments for now.