How to convert ZIO[R, Nothing, Boolean] to UIO[Boolean]?

76 views Asked by At

I just started learning ZIO and I'm having a difficult time finding the correct documentation. I obviously don't understand a core concept because this feels simple:

def getLastNameZio(firstName: String): URIO[R with ZMetrics with ZEnv, String] = {
  if (firstName == "bob") UIO("builder")
  else UIO("smith")
}

def isLastNameSmith(lastName: String): Boolean = {
  lastName == "smith"
}

def doWork(firstName: String): UIO[Boolean] = {
  for {
    lastName <- getLastNameZio(firstName)
    isSmithFamily = isLastNameSmith(lastName)
  } yield isSmithFamily // compiler complains
}

The compiler complains on that last line:

Required UIO [ Boolean ]
Found ZIO [ R, Nothing, Boolean ]

Why is this happening? I had to use for-comprehension otherwise the compiler will complain because lastName in doWork is a ZIO and can't just be inputted to isLastNameSmith

1

There are 1 answers

6
Gaël J On

Let's review the ZIO type aliases:

  • UIO[A] = ZIO[Any, Nothing, A]
  • URIO[R, A] = ZIO[R, Nothing, A]

The difference between the two being that one expects a R "context/requirement".

In your case, there's no reason for getLastNameZio to return a URIO, just stick with UIO.

Then a for comprehension like this can be just be written with a .map(...):

getLastNameZio(firstName).map(isLastNameSmith)

In a case where the URIO would make sense, you would need to either:

  • provide a R value right-away to get a UIO and then work with UIOs,
  • or, "propagate" the R type so that doWork returns a URIO, and provide a R value later (usually only at the top level in the "main" class)

There's a few ways to provide a R value. One of them is via ZLayers with something that usually looks like the following:

theUrio.provides(layerProvidingRValue)