Skip to Content
Course content

89: Extension Methods in Scala 3

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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 Invoice that adds:
    • isOverdue: Returns true if daysPending is 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 Invoice and print the results of these two new methods.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.