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
100: The Free Monad Pattern
I've spent a lot of time reviewing code from developers moving into high-level functional Scala, and there's a recurring pattern when they hit Free Monads: they think it's just a more verbose way of doing Dependency Injection. They'll tell me, "Why can't I just define a trait for my repository and inject a mock implementation for my tests?"
Free Monads Aren't Just Dependency Injection
If you use standard DI—say, passing a UserRepository trait into a service—you are binding your business logic to the execution of those effects. When you call repo.save(user), you're triggering a side effect immediately. The "program" is the act of calling the functions.
The Free Monad pattern is fundamentally different because it turns your program into a data structure. Instead of executing a save operation, you are building a tree of instructions that says "I would like to save this user."
Why does that distinction matter? Because when your program is just data, you can do things you can't do with DI. You can inspect the program, optimize it (like batching multiple database reads into one), or run the exact same sequence of logic through three different interpreters without ever changing a line of business code. You aren't injecting a dependency; you're separating the intent of the program from its execution.
Turning Logic Into Data via Algebra
To get this working, we first define our "Algebra"—basically a set of commands our program can issue. Let's imagine we're building a simple Order Processing system. We don't want the logic to know if we're using Postgres, MongoDB, or a HashMap in memory.
case class Order(id: String, amount: Double)
// This is our Algebra
sealed trait OrderOp[A] {
case class GetOrder(id: String) extends OrderOp[Order]
case class SaveOrder(order: Order) extends OrderOp[Unit]
case class LogMessage(msg: String) extends OrderOp[Unit]
}
Now, the "Free" part comes in. By wrapping this algebra in Free (which is essentially a recursive structure that allows us to chain these operations using flatMap), we can write a program that looks like standard imperative code but is actually just a nested object.
import cats.free.Free
import cats.impl.applicativeFunctors.Function1
// A helper to lift our algebra into the Free Monad
def getOrder(id: String): Free[OrderOp, Order] = Free.liftF(OrderOp.GetOrder(id))
def saveOrder(order: Order): Free[OrderOp, Unit] = Free.liftF(OrderOp.SaveOrder(order))
def logMsg(msg: String): Free[OrderOp, Unit] = Free.liftF(OrderOp.LogMessage(msg))
// This is our "Program". Note that NO actual DB calls happen here.
def processOrder(id: String): Free[OrderOp, Unit] = {
for {
order <- getOrder(id)
_ <- logMsg(s"Processing order ${order.id}")
_ <- saveOrder(order.copy(amount = order.amount * 0.9)) // 10% discount
_ <- logMsg("Discount applied and saved")
} yield ()
}
Separating the Algebra from the Interpreter
At this point, processOrder is just a value. It's a blueprint. To actually make it do something, we need an interpreter. This is where we map our OrderOp types to actual effects, like IO or Future.
I usually think of the interpreter as the "compiler" for my DSL. I can write one for production and one for testing.
import cats.effect.IO
// The Production Interpreter
def runProd[A](op: OrderOp[A]): IO[A] = op match {
case OrderOp.GetOrder(id) => IO.println(s"Querying DB for $id").as(Order(id, 100.0))
case OrderOp.SaveOrder(o) => IO.println(s"Writing $o to Postgres")
case OrderOp.LogMessage(m) => IO.println(s"[LOG]: $m")
}
// To run it, we use the 'foldMap' method provided by Free
val productionProgram = processOrder("order-123").foldMap(runProd)
If I wanted to test this, I wouldn't need a complex mocking framework. I'd just write a runTest interpreter that uses a State monad to track changes in a local map. The business logic in processOrder remains untouched and blissfully unaware of how it's being executed.
📋 Practical Task
Implement a Memory-Based FileSystem Interpreter
You are given a FileOp algebra that describes basic file system operations. Your task is to implement a runMemory interpreter that uses a scala.collection.mutable.Map to simulate a file system in memory, allowing you to test file logic without hitting the actual disk.
import cats.free.Free
import cats.effect.IO
sealed trait FileOp[A] {
case class ReadFile(path: String) extends FileOp[String]
case class WriteFile(path: String, content: String) extends FileOp[Unit]
case class DeleteFile(path: String) extends FileOp[Unit]
}
object FileSystem {
def readFile(path: String): Free[FileOp, String] = Free.liftF(FileOp.ReadFile(path))
def writeFile(path: String, content: String): Free[FileOp, Unit] = Free.liftF(FileOp.WriteFile(path, content))
def deleteFile(path: String): Free[FileOp, Unit] = Free.liftF(FileOp.DeleteFile(path))
}
// TODO: Implement this function
def runMemory[A](op: FileOp[A], storage: mutable.Map[String, String]): IO[A] = {
op match {
// Handle ReadFile: return value from map or throw error if missing
// Handle WriteFile: put value into map
// Handle DeleteFile: remove key from map
}
}
// Test your implementation with this program:
val program = for {
_ <- FileSystem.writeFile("test.txt", "Hello Free Monads!")
content <- FileSystem.readFile("test.txt")
_ <- FileSystem.deleteFile("test.txt")
} yield content
Requirements:
- The
ReadFilecase must return the string stored in the map for the given path. - The
WriteFilecase must update the map and returnIO.unit. - The
DeleteFilecase must remove the entry from the map and returnIO.unit. - The final output of
program.foldMap(op => runMemory(op, myMap))should be anIOthat resolves to"Hello Free Monads!".
There are no comments for now.