Exit e-book
Show all chapters
06
The ZLayer data type
06. 
The ZLayer data type

Sign up to our Newsletter

Signing up to our newsletter allows you to read all our ebooks.

I agree to receive marketing communication from Scalac.
You can unsubscribe from these communications at any time. For more information on how to unsubscribe, view our Privacy Policy.

Mastering Modularity in ZIO with Zlayer
06

The ZLayer data type

The ZLayer data type is an immutable value which contains a description to build an environment of type ROut, starting from a value RIn, possibly producing an error E during creation:

ZLayer[-RIn, +E, +ROut <: Has[_]]

Moreover, two layers can be combined in two fundamental ways:

  • Horizontally: To build a layer that has the requirements and provides the capabilities of both layers, we use the ++ operator.
  • Vertically: In this case, the output of one layer is used as input for the subsequent layer, resulting in a layer with the requirement of the first and the output of the second layer. We use the >>> operator for this.

Again, if this doesn’t make too much sense for you at this moment, don’t worry because we are going to be applying both horizontal and vertical composition when we reimplement the Tic-Tac-Toe application and everything will become clearer. And by the way, there are other additional operators for combining layers, and we are going to talk about them later.

Finally, it’s worth mentioning that ZIO provides some type aliases for the ZLayer data type which are very useful to represent some common use cases. The good news is that the logic for defining these type aliases is practically the same as that applied for defining the ZIO type aliases (for reference, you can take a look at the Quick Introduction to ZIO section of this article where I talk about concurrency with ZIO STM). Here’s the complete list:

  • TaskLayer[+ROut] = ZLayer[Any, Throwable, ROut]: This means a TaskLayer[ROut] is a ZLayer that:
    • Doesn’t require an input (that’s why the RIn type is replaced by Any)
    • Can fail with a Throwable
    • Can succeed with an ROut
  • ULayer[+ROut] = ZLayer[Any, Nothing, ROut]: This means a ULayer[ROut] is a ZLayer that:
    • Doesn’t require an input
    • Can’t fail
    • Can succeed with an ROut
  • RLayer[-RIn, +ROut] = ZLayer[RIn, Throwable, ROut]: This means an RLayer[RIn, ROut] is a ZLayer that:
    • Requires an input RIn
    • Can fail with a Throwable
    • Can succeed with an ROut
  • Layer[+E, +ROut] = ZLayer[Any, E, ROut]: This means a Layer[E, ROut] is a ZLayer that:
    • Doesn’t require an input
    • Can fail with an E
    • Can succeed with an ROut
  • URLayer[-RIn, +ROut] = ZLayer[RIn, Nothing, ROut]: This means a URLayer[RIn, ROut] is a ZLayer that:
    • Requires an input RIn
    • Can’t fail
    • Can succeed with an ROut
PREVIOUS
Chapter
05
NEXT
Chapter
07