🔴 Scala Intermediate

What are Scala's monads and how do they work?

Answer

A monad in Scala is a design pattern for sequencing computations with context. Any type with flatMap and unit (also called pure) that obeys monad laws is a monad. Common monads in Scala: Option: context = possible absence. Either: context = possible failure with error. Future: context = asynchronous computation. List: context = multiple values. IO (Cats Effect): context = side effects. The power of monads is that flatMap chains operations while threading the context automatically: findUser(id).flatMap(user => findOrder(user.orderId)).flatMap(order => sendEmail(order)). With for-comprehensions: for { user <- findUser(id); order <- findOrder(user.orderId); _ <- sendEmail(order) } yield (). Monads enable writing sequential-looking code that handles effects (None propagation, async, error handling) implicitly. The Cats library provides the Monad type class and many monad instances.