Skip to content

Commit

Permalink
Implement noneOrFail zio#4841
Browse files Browse the repository at this point in the history
  • Loading branch information
Michel Daviot committed Mar 31, 2021
1 parent 31234be commit 5ec9327
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 0 deletions.
35 changes: 35 additions & 0 deletions core-tests/shared/src/test/scala/zio/ZIOSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -1303,6 +1303,41 @@ object ZIOSpec extends ZIOBaseSpec {
assertM(ZIO.succeed(false).negate)(equalTo(true))
}
),
suite("noneOrFailWith")(
testM("on None succeeds with Unit") {
val option: Option[String] = None
val adaptError: String => String = identity
for {
value <- ZIO.noneOrFailWith(option, adaptError)
} yield {
assert(value)(equalTo(()))
}
},
testM("on Some fails") {
for {
value <- ZIO.noneOrFailWith(Some("value"), (v: String) => v + v).catchAll(e => ZIO.succeed(e))
} yield {
assert(value)(equalTo("valuevalue"))
}
} @@ zioTag(errors)
),
suite("noneOrFail")(
testM("on None succeeds with Unit") {
val option: Option[String] = None
for {
value <- ZIO.noneOrFail(option)
} yield {
assert(value)(equalTo(()))
}
},
testM("on Some fails") {
for {
value <- ZIO.noneOrFail(Some("value")).catchAll(e => ZIO.succeed(e))
} yield {
assert(value)(equalTo("value"))
}
} @@ zioTag(errors)
),
suite("once")(
testM("returns an effect that will only be executed once") {
for {
Expand Down
12 changes: 12 additions & 0 deletions core/shared/src/main/scala/zio/IO.scala
Original file line number Diff line number Diff line change
Expand Up @@ -730,6 +730,18 @@ object IO {
*/
val none: UIO[Option[Nothing]] = ZIO.none

/**
* @see See [[zio.ZIO.noneOrFailWith()]]
*/
def noneOrFailWith[E, O](o: Option[O], f: O => E): IO[E, Unit] =
ZIO.noneOrFailWith(o, f)

/**
* @see See [[zio.ZIO.noneOrFail()]]
*/
def noneOrFail[E](o: Option[E]): IO[E, Unit] =
ZIO.noneOrFail(o)

/**
* @see See [[zio.ZIO.not]]
*/
Expand Down
16 changes: 16 additions & 0 deletions core/shared/src/main/scala/zio/ZIO.scala
Original file line number Diff line number Diff line change
Expand Up @@ -3649,6 +3649,22 @@ object ZIO extends ZIOCompanionPlatformSpecific {
*/
val none: UIO[Option[Nothing]] = succeedNow(None)

/**
* Lifts an Option into a IO.
* If the option is empty it succeeds with Unit.
* If the option is defined it fails with the content.
*/
def noneOrFail[E](o: Option[E]): IO[E, Unit] =
getOrFailUnit(o).flip

/**
* Lifts an Option into a IO.
* If the option is empty it succeeds with Unit.
* If the option is defined it fails with an error adapted with f.
*/
def noneOrFailWith[E, O](o: Option[O], f: O => E): IO[E, Unit] =
getOrFailUnit(o).flip.mapError(f)

/**
* Feeds elements of type `A` to a function `f` that returns an effect.
* Collects all successes and failures in a tupled fashion.
Expand Down

0 comments on commit 5ec9327

Please sign in to comment.