Skip to content

Commit 82480c8

Browse files
committed
Add .tapFailure to TryOps
- works basically like `tapError` on Task - used to avoid doing `failed.foreach` on task, which creates an unnecessary exception on Try.Success
1 parent 80a2d81 commit 82480c8

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

core/src/main/scala/com/avsystem/commons/SharedExtensions.scala

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -461,6 +461,19 @@ object SharedExtensionsUtils extends SharedExtensions {
461461
*/
462462
def toOptArg: OptArg[A] =
463463
if (tr.isFailure) OptArg.Empty else OptArg(tr.get)
464+
465+
/**
466+
* Apply side-effect only if Try is a failure.
467+
*
468+
* Don't use .failed projection here, because it unnecessarily creates Exception in case of Success,
469+
* which is an expensive operation.
470+
*/
471+
def tapFailure(action: Throwable => Unit): Try[A] = tr match {
472+
case Success(_) => tr
473+
case Failure(throwable) =>
474+
action(throwable)
475+
tr
476+
}
464477
}
465478

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

0 commit comments

Comments
 (0)