001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018package org.apache.commons.lang3.function;
019
020import java.util.Objects;
021import java.util.function.BiFunction;
022import java.util.function.Function;
023
024/**
025 * A functional interface like {@link BiFunction} that declares a {@code Throwable}.
026 *
027 * @param <T> Input type 1.
028 * @param <U> Input type 2.
029 * @param <R> Return type.
030 * @param <E> Thrown exception.
031 * @since 3.11
032 */
033@FunctionalInterface
034public interface FailableBiFunction<T, U, R, E extends Throwable> {
035
036    /** NOP singleton */
037    @SuppressWarnings("rawtypes")
038    FailableBiFunction NOP = (t, u) -> null;
039
040    /**
041     * Returns The NOP singleton.
042     *
043     * @param <T> Consumed type 1.
044     * @param <U> Consumed type 2.
045     * @param <R> Return type.
046     * @param <E> Thrown exception.
047     * @return The NOP singleton.
048     */
049    static <T, U, R, E extends Throwable> FailableBiFunction<T, U, R, E> nop() {
050        return NOP;
051    }
052
053    /**
054     * Returns a composed {@code FailableBiFunction} that like {@link BiFunction#andThen(Function)}.
055     *
056     * @param <V> the output type of the {@code after} function, and of the composed function.
057     * @param after the operation to perform after this one.
058     * @return a composed {@code FailableBiFunction} that like {@link BiFunction#andThen(Function)}.
059     * @throws NullPointerException when {@code after} is null.
060     */
061    default <V> FailableBiFunction<T, U, V, E> andThen(final FailableFunction<? super R, ? extends V, E> after) {
062        Objects.requireNonNull(after);
063        return (final T t, final U u) -> after.apply(apply(t, u));
064    }
065
066    /**
067     * Applies this function.
068     *
069     * @param input1 the first input for the function
070     * @param input2 the second input for the function
071     * @return the result of the function
072     * @throws E Thrown when the function fails.
073     */
074    R apply(T input1, U input2) throws E;
075}