Skip to main content
Version: 2.x

Flattening Optional Error Types

If we have an optional error of type E in the error channel, we can flatten it to the E type using the ZIO#flattenErrorOption operator:

import zio._

def parseInt(input: String): ZIO[Any, Option[String], Int] =
if (input.isEmpty)
ZIO.fail(Some("empty input"))
else
try {
ZIO.succeed(input.toInt)
} catch {
case _: NumberFormatException => ZIO.fail(None)
}

def flattenedParseInt(input: String): ZIO[Any, String, Int] =
parseInt(input).flattenErrorOption("non-numeric input")

val r1: ZIO[Any, String, Int] = flattenedParseInt("zero")
val r2: ZIO[Any, String, Int] = flattenedParseInt("")
val r3: ZIO[Any, String, Int] = flattenedParseInt("123")

ZIO Chat

Hello! ๐Ÿ˜Š I'm your ZIO Chat Bot, designed to be your go-to resource for all things ZIO! Whether you're new to this powerful functional effect system or a seasoned pro, I'm here to assist you. ZIO empowers you to build concurrent and resilient applications in Scala, offering referential transparency, composable data types, type-safety, and more. So, go ahead and ask me anything about ZIO โ€“ I'm here to provide the answers you need! ๐Ÿค–