Composing ZIO
flatMap and for.
Sequencing with flatMap
ZIO is a monad, so flatMap chains effects where each step can use the previous result. The error and environment types combine automatically.
import zio._
val prog =
ZIO.succeed(10).flatMap(n => Console.printLine(s"n = $n"))for-comprehension
The for-comprehension is the idiomatic way to sequence ZIO effects, reading like imperative code while remaining pure.
import zio._
val prog = for {
_ <- Console.printLine("Enter name:")
name <- Console.readLine
_ <- Console.printLine(s"Hello, $name")
} yield ()