🔴 Scala
Beginner
What is the for-comprehension in Scala?
Answer
The for-comprehension in Scala is syntactic sugar for chains of map, flatMap, withFilter, and foreach calls. It provides a clean syntax for working with monadic types. Basic: for { x <- List(1,2,3); y <- List(10,20) } yield x + y is desugared to List(1,2,3).flatMap(x => List(10,20).map(y => x + y)). With Option: for { user <- findUser(id); email <- user.email } yield sendEmail(email) — returns None if any step returns None. With Future: chain async operations cleanly. Guards: for { n <- nums if n > 0 } yield n * 2. The for-comprehension works with any type implementing map, flatMap, and withFilter — making it a general monad comprehension syntax used extensively in functional Scala.