-
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
136: Practice Exercise: Building a Validated Form Parser with Cats
We've all been there: you're filling out a long registration form, you hit "Submit," and the page refreshes with a single error: "Invalid Email." You fix the email, hit submit again, and now it tells you "Password too short." You do this four or five times, getting hit with one error at a time, and by the time the form actually submits, you're already annoyed with the product. As developers, we often do this accidentally because we reach for the most familiar tool in our kit—the Either monad.
The fail-fast trap of Either
When I first started using Either for validation, it felt like the perfect fit. I could wrap each check in a function returning Either[String, A] and chain them together using a for comprehension. It's clean, it's readable, and it handles the "unhappy path" explicitly. But here is the problem: Either is designed for sequential computation. It is "fail-fast."
case class User(email: String, age: Int, username: String)
def validateEmail(email: String): Either[String, String] =
if (email.contains("@")) Right(email) else Left("Invalid email")
def validateAge(age: Int): Either[String, Int] =
if (age >= 18) Right(age) else Left("Must be at least 18")
def validateUsername(name: String): Either[String, String] =
if (name.length >= 3) Right(name) else Left("Username too short")
// The naive way: chaining with for-comprehensions
def parseUser(email: String, age: Int, name: String): Either[String, User] = {
for {
vEmail <- validateEmail(email)
vAge <- validateAge(age)
vName <- validateUsername(name)
} yield User(vEmail, vAge, vName)
}
If you pass an invalid email and an invalid age into this function, you'll only ever see the email error. The for comprehension stops at the first Left it encounters. In a backend API, this might be acceptable, but for a UI-driven form, it's a poor experience. We aren't just looking for the first thing that went wrong; we want a comprehensive list of everything that went wrong.
Accumulating errors with Validated
This is where cats.data.Validated comes in. Unlike Either, Validated isn't a monad—it's an applicative. I know that sounds like academic jargon, but in practical terms, it means Validated doesn't care about the result of the previous check to decide if it should run the current one. It allows us to run a set of independent checks and "accumulate" the failures.
To make this work, we use ValidatedNel[E, A]. The "Nel" stands for NonEmptyList. We use this instead of a standard List because if a validation fails, we know for a fact there is at least one error. It saves us from having to handle an empty list of errors in our logic.
import cats.data.ValidatedNel
import cats.implicits._
def validateEmailV(email: String): ValidatedNel[String, String] =
if (email.contains("@")) email.validNel else "Invalid email".invalidNel
def validateAgeV(age: Int): ValidatedNel[String, Int] =
if (age >= 18) age.validNel else "Must be at least 18".invalidNel
def validateUsernameV(name: String): ValidatedNel[String, String] =
if (name.length >= 3) name.validNel else "Username too short".invalidNel
def parseUserV(email: String, age: Int, name: String): ValidatedNel[String, User] = {
(
validateEmailV(email),
validateAgeV(age),
validateUsernameV(name)
).mapN(User.apply)
}
The trade-off: Sequence vs. Independence
You might be wondering why we don't just use Validated for everything. There is a real cost: you lose the ability to make one validation dependent on another. For example, if you have a field "Confirm Password," you can't validate that it matches the first password until you know the first password itself is valid. Validated cannot do this because it's not sequential.
My rule of thumb is this: if your validations are independent (like checking different fields in a form), use ValidatedNel. If you have a pipeline where step B requires the output of step A, stick with Either. In many complex systems, I actually use both—I'll use Validated to scrub the initial input and then convert the result to an Either using .toEither once I need to start performing sequential business logic.
📋 Practical Task
Exercise: Implementing a Comprehensive User Registration Validator with ValidatedNel
You are tasked with building a robust validation layer for a new user signup process. You need to ensure that the input data is clean before it ever hits your database.
Requirements:
- Create a case class
RegistrationDetails(email: String, age: Int, password: String, newsletter: Boolean). - Implement the following validation rules using
ValidatedNel[String, A]:- Email: Must contain both an '@' and a '.'
- Age: Must be between 13 and 120 (inclusive).
- Password: Must be at least 8 characters long and contain at least one digit.
- Write a function
validateRegistration(email: String, age: Int, password: String, newsletter: Boolean): ValidatedNel[String, RegistrationDetails]that aggregates all errors if any of the above rules fail. - Test your implementation with two scenarios:
- Input that is completely invalid (should return a
NonEmptyListcontaining three distinct error messages). - Input that is completely valid (should return the
RegistrationDetailsobject).
- Input that is completely invalid (should return a
Hint: Remember to import cats.implicits._ to get access to the mapN syntax and the .validNel / .invalidNel extension methods.
There are no comments for now.