From 8e2e2cbe63fd7cf7a30e76d5693e47aa0c427f31 Mon Sep 17 00:00:00 2001 From: Glavo Date: Mon, 23 Oct 2023 02:44:23 +0800 Subject: [PATCH] Close #71: Create Either::bifold --- .../src/main/java/kala/control/Either.java | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/kala-base/src/main/java/kala/control/Either.java b/kala-base/src/main/java/kala/control/Either.java index ce600e2c..873a81ae 100644 --- a/kala-base/src/main/java/kala/control/Either.java +++ b/kala-base/src/main/java/kala/control/Either.java @@ -9,6 +9,7 @@ import java.io.Serializable; import java.util.NoSuchElementException; import java.util.Objects; +import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; @@ -78,6 +79,13 @@ public abstract U fold( @NotNull Function rightMapper ); + public abstract U bifold( + @NotNull Either other, + U defaultValue, + @NotNull BiFunction leftMapper, + @NotNull BiFunction rightMapper + ); + @Contract("-> new") public abstract @NotNull Either swap(); @@ -190,6 +198,20 @@ public U fold( return leftMapper.apply(value); } + @Override + public U bifold( + @NotNull Either other, + U defaultValue, + @NotNull BiFunction leftMapper, + @NotNull BiFunction rightMapper) { + + if (other instanceof Left) { + return leftMapper.apply(this.value, ((Left) other).value); + } else { + return defaultValue; + } + } + /** * {@inheritDoc} */ @@ -332,6 +354,20 @@ public U fold( return rightMapper.apply(value); } + @Override + public U bifold( + @NotNull Either other, + U defaultValue, + @NotNull BiFunction leftMapper, + @NotNull BiFunction rightMapper) { + + if (other instanceof Right) { + return rightMapper.apply(this.value, ((Right) other).value); + } else { + return defaultValue; + } + } + /** * {@inheritDoc} */