home search about rss feed twitter ko-fi

How Either Relates to ZIO (Scala 3 Video)

As I mentioned, if all of this continues to make sense, you’re so close to functional programming right now, you can almost taste it. The truth is this: if you can handle Either, you can handle FP.

A look at ZIO

If you haven’t heard of it before, ZIO is one of the two main FP libraries in the Scala community (along with the other, named Cats Effect). These two libraries power some of the busiest websites on the internet, including Disney Streaming, Caesars, and many other sites and applications here in 2022.

What I mean when I say “you’re so close to FP that you can taste it” is that if you look at the ZIO Overview document in November, 2022 — and pretty much every other “introduction to ZIO” article on the internet — you’ll see that all the authors start with a description like this:

Conceptually, you can think of the ZIO type as being a function that takes a generic R data type, and returns an Either.

That sentence means that conceptually you can sketch a ZIO function signature to look like this:

def ZIO(r: R): Either[E, A]

While that code isn’t really how ZIO works, the basic idea is that you can think of:

  • The ZIO type as taking a generic R type as an input parameter.
  • It returns an Either.
  • Inside the Either, you see that it has two generic types in the Left and Right positions:
Either[E,     A]
       ^      ^
      Left  Right

These generic types are given the names R, E, and A for very specific reasons:

  • R stands for the environment that is passed in. Basically if your code requires some sort of environment, like a database, input/output, or even a clock, you pass in the dependencies your code needs as the R parameter. (It may help to think of this parameter being named D, for dependencies.)
  • E is the usual Either error-handling type, i.e., the type in the Left position. Having seen Either in the previous lessons, you already know what this means. (As usual, think of it as the “unhappy” result.)
  • Similarly, A is the success data type that you really want, i.e., the “happy path” or “happy result.” (If your algorithm returns an Int as its success value, you return it in this position.)

So this is what I mean when I say that if you understand Either, you’re now ready to start using ZIO and Cats Effect.

At this point, to keep things simple, I’ll just keep referring to ZIO, but unless I’m showing a ZIO-specific example, every time you see “ZIO” you can think, “Cats Effect and ZIO.”

Coding with ZIO just involves using types like this, and again, you’re really a mathematician who’s writing algebra, or an architect writing blueprints. Your code is incredibly honest because it’s all immutable variables, immutable data structures, pure functions you can trust — along with descriptive data types — expression-oriented code, and functional error handling.

Update: All of my new videos are now on
LearnScala.dev