0Pricing
Scala for Backend Engineering & Functional Programming · Lesson

Composing ZIO

flatMap and for.

Composing ZIO is a free Scala for Backend Engineering & Functional Programming lesson on CoddyKit — lesson 2 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.

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 ()

Combining Error Types

When you compose two effects with different error types E1 and E2, ZIO infers the least upper bound E1 with E2's common supertype, often Throwable or a sealed trait.

zip and zipPar

zip combines two effects into a tuple sequentially. zipPar runs them concurrently on separate fibers.

import zio._

val seq: UIO[(Int, Int)] = ZIO.succeed(1).zip(ZIO.succeed(2))
val par: UIO[(Int, Int)] = ZIO.succeed(1).zipPar(ZIO.succeed(2))

zipRight and zipLeft

*> (zipRight) keeps the second result; <* (zipLeft) keeps the first. Both run effects in order.

import zio._

val r = Console.printLine("log") *> ZIO.succeed(99)

foreach

ZIO.foreach runs an effect for each element of a collection and gathers the results, like a traverse.

import zio._

val prog = ZIO.foreach(List(1, 2, 3))(n => Console.printLine(n.toString))

foreachPar

ZIO.foreachPar runs each element's effect concurrently — ideal for parallel I/O such as multiple HTTP requests.

import zio._

val ids = List(1, 2, 3)
val prog = ZIO.foreachPar(ids)(id => ZIO.succeed(id * 10))

Conditional Effects

ZIO.when runs an effect only if a condition is true, returning Option of the result. ZIO.unless is the inverse.

import zio._

def logIf(debug: Boolean) =
  ZIO.when(debug)(Console.printLine("debugging"))

Looping

ZIO.iterate and ZIO.loop build effectful loops. repeatN reruns an effect a fixed number of times.

import zio._

val ticks = Console.printLine("tick").repeatN(2) // runs 3 times total

A Composed Workflow

Here a workflow computes a sum and prints it, composed entirely from small ZIO steps in a for-comprehension.

import zio._

val workflow = for {
  a <- ZIO.succeed(20)
  b <- ZIO.succeed(22)
  _ <- Console.printLine(s"Sum: ${a + b}")
} yield ()

Plain Scala Equivalent

The same logic in eager plain Scala for comparison. ZIO defers and tracks effects in the type system, but produces identical output.

object Main {
  def main(args: Array[String]): Unit = {
    val a = 20
    val b = 22
    println(s"Sum: ${a + b}")
  }
}

Quick Check

Which combinator runs an effect for each element of a list concurrently?

Recap

You composed ZIO effects with:

  • flatMap / for for sequencing
  • zip / zipPar, *>, <*
  • foreach / foreachPar
  • when / unless and looping

Next: the error and dependency channels.

Frequently asked questions

Is the “Composing ZIO” lesson free?

Yes — the full text of “Composing ZIO” 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 “Composing ZIO”?

flatMap and for. 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 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Composing ZIO” 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

  1. The ZIO Effect
  2. Composing ZIO
  3. Error and Dependency Channels
  4. Running ZIO Apps
← Back to Scala for Backend Engineering & Functional Programming