Skip to Content
Course content

93: Given/Using Clauses In Depth

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

By now, you know that given and using are the Scala 3 replacements for the old implicit keyword. But once you move past simple "Hello World" examples, you start noticing that the compiler's search logic can be a bit opaque. Let's dig into how this actually works under the hood.

How does the compiler actually decide which given to use when there are multiple options?

I've seen a lot of developers get frustrated when the compiler complains about "ambiguous implicit values." This usually happens when you have two given instances that could both satisfy a using clause. The compiler doesn't just flip a coin; it looks for the most specific type.

Look at this example where we're handling report formatting. We have a general formatter and a specialized one for currency:

case class ReportConfig(precision: Int)
case class CurrencyConfig(symbol: String, precision: Int) extends ReportConfig(precision)

given generalConfig: ReportConfig = ReportConfig(2)
given currencyConfig: CurrencyConfig = CurrencyConfig("$", 2)

def printValue(value: Double)(using config: ReportConfig) = 
  println(s"Value: ${value} (Precision: ${config.precision})")

def printMoney(value: Double)(using config: CurrencyConfig) = 
  println(s"Money: ${config.symbol}${value} (Precision: ${config.precision})")

printValue(10.5)  // Uses generalConfig
printMoney(10.5)  // Uses currencyConfig

If I called printValue(10.5), the compiler sees that both generalConfig and currencyConfig (since it extends ReportConfig) fit the bill. However, it will prioritize the most specific match. If they are equally specific, it crashes. If you find yourself in a tie, you can't just "hope" for the best—you'll need to explicitly import the one you want or define a more specific type.

Can I define a given inside a method, and why would I bother?

Absolutely. You can define a given anywhere—including inside a function body. I do this all the time when I want to "override" a global default for a specific block of logic without affecting the rest of the application.

Imagine you have a global timeout for your API calls, but one specific legacy endpoint is incredibly slow and needs more time. You don't want to change the global config for everyone, just for this one call:

case class Timeout(ms: Int)
given globalTimeout: Timeout = Timeout(1000)

def fetchRemoteData(url: String)(using t: Timeout) = 
  println(s"Fetching $url with timeout ${t.ms}ms")

def legacyIntegration() = {
  // Local given shadows the global one within this scope
  given localTimeout: Timeout = Timeout(5000) 
  fetchRemoteData("https://legacy-system.com/api")
}

def modernIntegration() = {
  fetchRemoteData("https://fast-system.com/api")
}

legacyIntegration() // Prints 5000ms
modernIntegration() // Prints 1000ms

The localTimeout is only visible to expressions inside the legacyIntegration method. It's a clean way to handle context-specific overrides without passing parameters through ten different function calls.

What is the difference between using a using clause in a method versus a class constructor?

This is where people often get tripped up. When you put a using clause in a method, it's just a requirement for that specific call. But when you put it in a class constructor, the instance of that class "captures" the given value for its entire lifetime.

Think of it as a way to bake the environment into the object. Here's how that looks in practice:

case class DatabaseContext(connectionString: String)

class UserRepo(using ctx: DatabaseContext) {
  def findUser(id: Int) = 
    println(s"Querying ${ctx.connectionString} for user $id")
}

given defaultCtx: DatabaseContext = DatabaseContext("jdbc:postgresql://localhost:5432/db")

// The compiler finds 'defaultCtx' and injects it into the constructor
val repo = new UserRepo() 
repo.findUser(1)

In the example above, UserRepo doesn't need to ask for the DatabaseContext every time findUser is called. It already has it stored as a field because the using clause was in the constructor. This is essentially Dependency Injection, but handled by the Scala compiler instead of a heavy framework like Spring.




📋 Practical Task

Exercise: Building a Multi-Currency Price Formatter

You need to create a system that formats prices based on a CurrencyContext. Your goal is to implement a system where the formatter can be swapped out depending on the locale without changing the business logic.

Requirements:

  • Create a case class CurrencyContext(symbol: String, locale: String).
  • Define a given instance for USD (symbol: "$", locale: "en-US").
  • Define a given instance for EUR (symbol: "€", locale: "de-DE").
  • Create a class PriceFormatter(using ctx: CurrencyContext). This class should have a method format(amount: Double): String that returns a string like "$100.00 (en-US)".
  • In your main execution block:
    • Instantiate a PriceFormatter using the USD context.
    • Instantiate a PriceFormatter using a locally defined given for GBP (symbol: "£", locale: "en-GB").
    • Print the formatted results of both to verify they are using the correct contexts.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.