Skip to content

Commit

Permalink
Close #71: Create Either::bifold
Browse files Browse the repository at this point in the history
  • Loading branch information
Glavo committed Oct 22, 2023
1 parent aa1aa2c commit 8e2e2cb
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions kala-base/src/main/java/kala/control/Either.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -78,6 +79,13 @@ public abstract <U> U fold(
@NotNull Function<? super B, ? extends U> rightMapper
);

public abstract <C, D, U> U bifold(
@NotNull Either<? extends C, ? extends D> other,
U defaultValue,
@NotNull BiFunction<? super A, ? super C, ? extends U> leftMapper,
@NotNull BiFunction<? super B, ? super D, ? extends U> rightMapper
);

@Contract("-> new")
public abstract @NotNull Either<B, A> swap();

Expand Down Expand Up @@ -190,6 +198,20 @@ public <U> U fold(
return leftMapper.apply(value);
}

@Override
public <C, D, U> U bifold(
@NotNull Either<? extends C, ? extends D> other,
U defaultValue,
@NotNull BiFunction<? super A, ? super C, ? extends U> leftMapper,
@NotNull BiFunction<? super B, ? super D, ? extends U> rightMapper) {

if (other instanceof Left) {
return leftMapper.apply(this.value, ((Left<? extends C, ? extends D>) other).value);
} else {
return defaultValue;
}
}

/**
* {@inheritDoc}
*/
Expand Down Expand Up @@ -332,6 +354,20 @@ public <U> U fold(
return rightMapper.apply(value);
}

@Override
public <C, D, U> U bifold(
@NotNull Either<? extends C, ? extends D> other,
U defaultValue,
@NotNull BiFunction<? super A, ? super C, ? extends U> leftMapper,
@NotNull BiFunction<? super B, ? super D, ? extends U> rightMapper) {

if (other instanceof Right) {
return rightMapper.apply(this.value, ((Right<? extends C, ? extends D>) other).value);
} else {
return defaultValue;
}
}

/**
* {@inheritDoc}
*/
Expand Down

0 comments on commit 8e2e2cb

Please sign in to comment.