Skip to content

Commit

Permalink
Add .tapFailure to TryOps
Browse files Browse the repository at this point in the history
- works basically like `tapError` on Task
- used to avoid doing `failed.foreach` on task, which creates an unnecessary exception on Try.Success
  • Loading branch information
najder-k committed Jul 25, 2024
1 parent 80a2d81 commit 82480c8
Showing 1 changed file with 13 additions and 0 deletions.
13 changes: 13 additions & 0 deletions core/src/main/scala/com/avsystem/commons/SharedExtensions.scala
Original file line number Diff line number Diff line change
Expand Up @@ -461,6 +461,19 @@ object SharedExtensionsUtils extends SharedExtensions {
*/
def toOptArg: OptArg[A] =
if (tr.isFailure) OptArg.Empty else OptArg(tr.get)

/**
* Apply side-effect only if Try is a failure.
*
* Don't use .failed projection here, because it unnecessarily creates Exception in case of Success,
* which is an expensive operation.
*/
def tapFailure(action: Throwable => Unit): Try[A] = tr match {
case Success(_) => tr
case Failure(throwable) =>
action(throwable)
tr
}
}

class LazyTryOps[A](private val tr: () => Try[A]) extends AnyVal {
Expand Down

0 comments on commit 82480c8

Please sign in to comment.