By Alvin Alexander. Last updated: January 28, 2024
As a brief note, here’s an example of the ZIO (ZIO 2) collectAll
method.
To make things more interesting, I also show several examples of how to use ZIO types and type aliases, both with the printLine
function and the theEnd
value at the end:
//> using scala "3"
//> using lib "dev.zio::zio::2.0.19"
// Set up your IDE:
// scala-cli setup-ide .
// Run me like this:
// scala-cli ThisFilename.scala
// `Task[A]` is a type alias for `ZIO[Any, Throwable, A]`
// `UIO[A]` is a type alias for `ZIO[Any, Nothing, A]`
import zio.{Task, UIO, ZIO, ZIOAppDefault}
/**
* This started as a ZIO `collectAll` example, and it also shows
* type alternatives on the `printLine` function and the `theEnd` result.
*/
object ZioCollectAll extends ZIOAppDefault:
// `ZIO.attempt` yields either of these types:
// -------------------------------------------
// def printLine(line: String): Task[Unit] = ZIO.attempt(println(line))
// def printLine(line: String): ZIO[Any, Throwable, Unit] = ZIO.attempt(println(line))
// `ZIO.succeed` yields either of these types:
// -------------------------------------------
// def printLine(line: String): ZIO[Any, Nothing, Unit] = ZIO.succeed(println(line))
def printLine(line: String): UIO[Unit] = ZIO.succeed(println(line))
val run =
val rez: ZIO[Any, Nothing, List[Int]] = ZIO.collectAll(
List(
ZIO.succeed(1),
ZIO.succeed(2),
ZIO.succeed(3)
)
)
// when `printLine` uses `ZIO.attempt`, use either of these:
// ---------------------------------------------------------
// val theEnd = rez.flatMap(sum => printLine(s"$sum"))
// val theEnd: ZIO[Any, Throwable, Unit] = rez.flatMap(sum => printLine(s"$sum"))
// val theEnd: Task[Unit] = rez.flatMap(sum => printLine(s"$sum"))
// when `printLine` uses `ZIO.succeed`, use either of these:
// ---------------------------------------------------------
// val theEnd = rez.flatMap(sum => printLine(s"$sum"))
// val theEnd: ZIO[Any, Nothing, Unit] = rez.flatMap(sum => printLine(s"$sum"))
val theEnd: UIO[Unit] = rez.flatMap(sum => printLine(s"$sum"))
theEnd
this post is sponsored by my books: | |||
#1 New Release |
FP Best Seller |
Learn Scala 3 |
Learn FP Fast |
You can find more details about the ZIO on this ZIO Reference page and this ZIO Scaladoc page.