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
93: Given/Using Clauses In Depth
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
giveninstance forUSD(symbol: "$", locale: "en-US"). - Define a
giveninstance forEUR(symbol: "€", locale: "de-DE"). - Create a class
PriceFormatter(using ctx: CurrencyContext). This class should have a methodformat(amount: Double): Stringthat returns a string like"$100.00 (en-US)". - In your main execution block:
- Instantiate a
PriceFormatterusing theUSDcontext. - Instantiate a
PriceFormatterusing a locally definedgivenforGBP(symbol: "£", locale: "en-GB"). - Print the formatted results of both to verify they are using the correct contexts.
- Instantiate a
There are no comments for now.