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
175: Context Functions in Scala 3
You've likely spent a fair amount of time using using clauses in Scala 3 to handle dependency injection or configuration. It works, but it has a "viral" quality: if a function at the bottom of your call stack needs a RequestContext, every single function above it in the chain must also declare using ctx: RequestContext just to pass it along. It's tedious, and it clutters your method signatures.
Context functions (introduced as a way to make "contextual abstractions" first-class citizens) solve this by allowing you to define a type that is a function expecting an implicit value. Instead of a method that uses a context, you create a method that returns a context-aware computation.
The "Why isn't this executing?" bug
When I first started using context functions, I made a mistake that almost every developer makes. I confused a function that requires a context with a function that returns a context function. Look at this code for a database session manager:
case class DbSession(id: String)
// We define a type alias for a context function
type DbAction[A] = DbSession ?=> A
def fetchUserName(userId: Int): DbAction[String] = {
val session = summon[DbSession]
s"User $userId fetched via session ${session.id}"
}
def main(): Unit = {
given DbSession("session-123")
// I expected this to print: "User 42 fetched via session session-123"
println(fetchUserName(42))
}
If you run this, you won't see the user's name. Instead, you'll see something like DbAction(Function1). Why? Because fetchUserName didn't actually execute the logic; it returned a function object that is waiting for a DbSession to be provided.
I had fallen into the trap of treating the context function as if it were a regular method with a using parameter. In a regular method, the implicit is resolved at the moment the method is called. In a context function, the ?=> syntax means the function itself is the value being returned, and it won't execute its body until that function is actually invoked.
Invoking the context function
To fix this, you have to realize that fetchUserName(42) returns a function of type DbSession => String. To get the string out, you need to call that returned function. Since we have a given DbSession in scope, Scala 3 can handle this automatically if we apply the function.
Here is the corrected version:
case class DbSession(id: String)
type DbAction[A] = DbSession ?=> A
def fetchUserName(userId: Int): DbAction[String] = {
val session = summon[DbSession]
s"User $userId fetched via session ${session.id}"
}
def main(): Unit = {
given DbSession("session-123")
// Notice the extra parentheses!
// fetchUserName(42) returns the context function.
// The second set of () invokes it, pulling the 'given' from the scope.
val result = fetchUserName(42)(using summon[DbSession])
// Or more simply, if you are in a context where you can just apply it:
val simpleResult = fetchUserName(42)
// Wait, this still returns the function. To run it:
println(fetchUserName(42)(summon[DbSession]))
}
Actually, the most common way to use these is to have a "runner" that handles the execution, which keeps the business logic clean of the plumbing.
Decoupling execution from definition
The real power here isn't just avoiding using in signatures; it's the ability to pass the "intent" to do something around without providing the context yet. I prefer to create a run method that manages the lifecycle of the context.
case class DbSession(id: String)
type DbAction[A] = DbSession ?=> A
object DbRunner {
def run[A](action: DbAction[A], session: DbSession): A = {
// We provide the session as a given locally, then call the action
given DbSession = session
action
}
}
def fetchUserName(userId: Int): DbAction[String] = {
val session = summon[DbSession]
s"User $userId fetched via session ${session.id}"
}
def updateLastLogin(userId: Int): DbAction[Unit] = {
val session = summon[DbSession]
println(s"Updating user $userId in session ${session.id}")
}
// Now we can compose these without mentioning DbSession in the signatures
def userMaintenance(userId: Int): DbAction[String] = {
updateLastLogin(userId)
fetchUserName(userId)
}
def main(): Unit = {
val session = DbSession("prod-db-01")
val name = DbRunner.run(userMaintenance(42), session)
println(name)
}
Notice how userMaintenance doesn't need to know how to create a session or even explicitly pass one along. It just returns a DbAction. We've successfully separated the description of the work from the execution of the work.
T ?=> A: This is the type of a context function. It means "a function that, given an implicitT, returns anA".summon[T]: Used inside the context function to grab the actual value of the context.- First-class status: Because
DbAction[A]is just a type alias for a function, you can put it in a List, pass it to other functions, or map over it.
📋 Practical Task
Building a Context-Aware Permission Guard
You are building a security layer for an API. Instead of passing a User object through every single service method, you want to use a Context Function to handle authorization.
Requirements:
- Define a
case class User(name: String, isAdmin: Boolean). - Create a type alias
type AuthAction[A] = User ?=> A. - Implement a function
deleteDatabase(): AuthAction[String]. Inside this function:- Use
summon[User]to check the current user. - If the user is an admin, return
"Database deleted successfully". - If the user is not an admin, throw a
RuntimeException("Unauthorized").
- Use
- Implement a function
viewProfile(userId: Int): AuthAction[String]that returnss"Profile for $userId"(this should be accessible to any user). - Create a
SecurityRunnerobject with a methodrun[A](action: AuthAction[A], user: User): Athat executes the action using the provided user. - In your
mainmethod, test bothviewProfileanddeleteDatabasewith both an admin user and a regular user to verify that the permission guard works correctly.
There are no comments for now.