Using with Option and Future
Monadic chaining.
Using with Option and Future is a free Scala for Backend Engineering & Functional Programming lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Scala for Backend Engineering & Functional Programming learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Beyond collections
For-comprehensions are not limited to lists. Any type that provides map and flatMap can be used, including Option, Either, Try, and Future. This is called monadic chaining.
object Main {
def main(args: Array[String]): Unit = {
val sum = for {
a <- Some(10)
b <- Some(20)
} yield a + b
println(sum)
}
}Option short-circuits on None
With Option, the comprehension produces a result only if every generator is Some. If any is None, the whole result is None and later steps are skipped.
object Main {
def main(args: Array[String]): Unit = {
val ok = for {
a <- Some(2)
b <- Some(3)
} yield a * b
val missing = for {
a <- Some(2)
b <- None: Option[Int]
} yield a * b
println(ok)
println(missing)
}
}Chaining optional lookups
A common pattern: look up keys in a Map, where each lookup returns an Option. The for-comprehension yields a value only if all lookups succeed.
object Main {
def main(args: Array[String]): Unit = {
val prices = Map("apple" -> 3, "bread" -> 5)
val total = for {
a <- prices.get("apple")
b <- prices.get("bread")
} yield a + b
println(total)
val missing = for {
a <- prices.get("apple")
c <- prices.get("milk")
} yield a + c
println(missing)
}
}Why this beats nested if-else
Without for-comprehensions you would nest pattern matches or null checks. The monadic form flattens that pyramid into a clean linear sequence.
object Main {
def parse(s: String): Option[Int] = s.toIntOption
def main(args: Array[String]): Unit = {
val result = for {
x <- parse("40")
y <- parse("2")
} yield x + y
println(result)
}
}Guards work with Option too
A guard inside an Option comprehension turns a value into None when the condition fails, acting as inline validation.
object Main {
def main(args: Array[String]): Unit = {
def validate(age: Int): Option[Int] =
for {
a <- Some(age)
if a >= 18
} yield a
println(validate(25))
println(validate(15))
}
}Introducing Future
A Future represents a value that will be available later. Like Option, it has map and flatMap, so for-comprehensions sequence asynchronous steps.
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Await
import scala.concurrent.duration._
object Main {
def main(args: Array[String]): Unit = {
val f = for {
a <- Future(10)
b <- Future(20)
} yield a + b
println(Await.result(f, 2.seconds))
}
}Futures run sequentially here
When one generator depends on another inside a for-comprehension, the futures run in sequence because each flatMap waits for the previous result.
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Await
import scala.concurrent.duration._
object Main {
def main(args: Array[String]): Unit = {
val f = for {
a <- Future(5)
b <- Future(a * 2)
} yield a + b
println(Await.result(f, 2.seconds))
}
}Running futures in parallel
To run futures in parallel, start them before the for-comprehension, then combine. Independent work overlaps instead of waiting.
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Await
import scala.concurrent.duration._
object Main {
def main(args: Array[String]): Unit = {
val fa = Future(100)
val fb = Future(200)
val combined = for {
a <- fa
b <- fb
} yield a + b
println(Await.result(combined, 2.seconds))
}
}Either for richer errors
Either[E, A] carries an error value on failure. In a for-comprehension, the first Left short-circuits and is returned.
object Main {
def parse(s: String): Either[String, Int] =
s.toIntOption.toRight(s"not a number: $s")
def main(args: Array[String]): Unit = {
val good = for { a <- parse("3"); b <- parse("4") } yield a + b
val bad = for { a <- parse("3"); b <- parse("x") } yield a + b
println(good)
println(bad)
}
}The same shape, many types
Notice the comprehension looks identical whether you use Option, Either, Try, or Future. Only the failure semantics differ. This uniformity is the power of monadic chaining.
import scala.util.Try
object Main {
def main(args: Array[String]): Unit = {
val result = for {
a <- Try("21".toInt)
b <- Try("2".toInt)
} yield a * b
println(result)
}
}Mixing types is not allowed
All generators in one comprehension must be the same monad. You cannot mix an Option generator with a Future generator directly; convert one first (for example Future.fromTry or wrap the Option).
object Main {
def main(args: Array[String]): Unit = {
// Convert the Option to keep types consistent
val maybe: Option[Int] = Some(7)
val result = for {
a <- maybe
b <- maybe.map(_ + 1)
} yield a + b
println(result)
}
}Quick Check
In an Option for-comprehension, what happens if one generator yields None?
Recap
You learned monadic chaining with for-comprehensions:
- Works on any type with
mapandflatMap Optionshort-circuits onNoneEitherandTryshort-circuit on failure, carrying error infoFuturesequences async steps; start them early for parallelism- All generators must share the same monad type
Frequently asked questions
Is the “Using with Option and Future” lesson free?
Yes — the full text of “Using with Option and Future” is free to read here on the web, and the Scala for Backend Engineering & Functional Programming course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Scala for Backend Engineering & Functional Programming course, upgrade to CoddyKit PRO.
What will I learn in “Using with Option and Future”?
Monadic chaining. You practise Scala for Backend Engineering & Functional Programming with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Scala for Backend Engineering & Functional Programming?
No prior experience is required. Scala for Backend Engineering & Functional Programming on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Using with Option and Future” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Scala for Backend Engineering & Functional Programming lesson?
Yes. Every Scala for Backend Engineering & Functional Programming lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Desugaring for
- Filtering with if
- Multiple Generators
- Using with Option and Future