-
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
248: Practice Exercise: Modeling an Inventory System with Refined Types
I've spent a lot of time maintaining legacy inventory systems, and if there is one thing I've learned, it's that Int and String are far too broad for the real world. In a warehouse, a "quantity" of -5 doesn't make sense, and a "SKU" that's just an empty string is a recipe for a database nightmare. Usually, we handle this with a mountain of if statements or validation logic scattered across the service layer.
Let's try to model a simple product record and see where the cracks appear.
The danger of the naked Int
case class Product(sku: String, quantity: Int, price: Double)
val item = Product(sku = "INVALID_SKU!", quantity = -10, price = -5.0)
println(s"Added $item to inventory")
The compiler is perfectly happy with this. But as far as the business is concerned, this object is a lie. I can pass this item into a shipping function, and suddenly my system thinks I've shipped negative ten items and paid the customer five dollars to take them. I could write a validate() method, but that's an opt-in check. I'd rather make it impossible to even construct an invalid product.
Adding guards with Refined
Since we've touched on the refined library in previous lessons, let's see if we can tighten this up. I want the quantity to be non-negative and the price to be strictly positive. I'll try swapping those primitives for refined types.
import eu.refined.api.Refined
import eu.refined.collection.CSeq
import eu.refined.numeric.Positive
import eu.refined.numeric.NonNegative
case class Product(
sku: String,
quantity: Refined[NonNegative, Int],
price: Refined[Positive, Double]
)
// This won't compile if I try to pass a raw Int
// val item = Product("SKU123", 10, 19.99)
Right away, I hit a wall. I can't just pass 10. The compiler tells me it expects a Refined[NonNegative, Int], not an Int. This is the core trade-off: we've traded convenience for a guarantee. To actually create this object, I have to explicitly refine the value.
Dealing with the runtime reality
Now I have to figure out how to get my raw data (maybe from a JSON API or a database) into these types. I'll use the refineV method, which returns an Either. This is where the "live" part of the validation actually happens.
import eu.refined.refine def createProduct(sku: String, q: Int, p: Double) = { for { qty <- refineV[NonNegative](q) prc <- refineV[Positive](p) } yield Product(sku, qty, prc) } val result = createProduct("SKU123", -5, 10.0) // result is Left(RefinementError(...)) because -5 is not NonNegativeThis is much better. The
Productcase class now acts as a "trusted" object. If I have an instance ofProductin my hand, I know for a fact that the quantity isn't negative. I don't have to check it again in theshipItemorcalculateValuefunctions.Taming the SKU format
The
skuis still a rawString, which is bothering me. In my hypothetical warehouse, a SKU must be exactly 5 uppercase letters followed by a hyphen and 4 digits (e.g., "PROD1-1234"). A standardStringwon't cut it. I need a custom predicate.I'll try defining a custom refinement. This requires creating a class that extends
Predicate.import eu.refined.Predicate case class IsSKU() extends Predicate[String] { override def refine(value: String): Either[String, String] = { if (value.matches("^[A-Z]{5}-\\d{4}$")) Right(value) else Left(s"$value is not a valid SKU format (Expected: ABCDE-1234)") } } // Now let's update our Product model case class Product( sku: Refined[IsSKU, String], quantity: Refined[NonNegative, Int], price: Refined[Positive, Double] )Now, my domain model is essentially a set of rules. If I try to create a
Productwith a SKU like "apple-123", therefineV[IsSKU]("apple-123")call will fail. The beauty here is that the "rules" are now part of the type signature. If I seeRefined[IsSKU, String]in a function signature, I don't need to ask the original author "Wait, what's the format for the SKU?"βthe code tells me exactly what it is.
π Practical Task
Exercise: Implementing a Validated Warehouse Stock Update
You are building a stock management module. You need to implement a function that updates the quantity of a product, but it must maintain the integrity of the refined types.
Requirements:
- Use the
refinedlibrary. - Define a
Productcase class with:sku: Refined as aStringthat must match the regex"^[A-Z]{3}-\\d{3}$"(e.g., "ABC-123").quantity: Refined asNonNegativeInt.
- Implement a function
updateStock(product: Product, change: Int): Either[String, Product]. - The
updateStockfunction should:- Calculate the new quantity (current quantity + change).
- Attempt to refine the new quantity as
NonNegative. - If refinement succeeds, return the updated
Product. - If refinement fails (i.e., the change would make the stock negative), return a
Leftwith a descriptive error message.
Test Case:
Creating a product with SKU "XYZ-789" and quantity 10, then calling updateStock with -15 should result in a Left error.
There are no comments for now.