From 82480c841bf5e3ba98673a2e919f241cb129a10f Mon Sep 17 00:00:00 2001 From: Konrad Najder Date: Thu, 25 Jul 2024 13:48:45 +0200 Subject: [PATCH] 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 --- .../com/avsystem/commons/SharedExtensions.scala | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/core/src/main/scala/com/avsystem/commons/SharedExtensions.scala b/core/src/main/scala/com/avsystem/commons/SharedExtensions.scala index 5c3bb37b4..4f0a6f611 100644 --- a/core/src/main/scala/com/avsystem/commons/SharedExtensions.scala +++ b/core/src/main/scala/com/avsystem/commons/SharedExtensions.scala @@ -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 {