All Downloads are FREE. Search and download functionalities are using the official Maven repository.

pl.touk.throwing.ThrowingBiFunction Maven / Gradle / Ivy

There is a newer version: 1.6.1
Show newest version
/*
 * Copyright 2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package pl.touk.throwing;

import pl.touk.throwing.exception.WrappedException;

import java.util.Objects;
import java.util.Optional;
import java.util.function.BiFunction;


/**
 * Represents a function that accepts two arguments and produces a result.
 * This is the two-arity specialization of {@link ThrowingFunction}.
 * Function may throw a checked exception.
 *
 * @param  the type of the first argument to the function
 * @param  the type of the second argument to the function
 * @param  the type of the result of the function
 * @param  the type of the thrown checked exception
 *
 * @see ThrowingFunction
 */
@FunctionalInterface
public interface ThrowingBiFunction {
    R apply(T1 arg1, T2 arg2) throws E;

    static  BiFunction unchecked(ThrowingBiFunction function) {
        Objects.requireNonNull(function);

        return function.unchecked();
    }

    static  BiFunction> lifted(ThrowingBiFunction f) {
        Objects.requireNonNull(f);

        return f.lift();
    }

    /**
     * Performs provided action on the result of this ThrowingBiFunction instance
     * @param after action that is supposed to be made on the result of apply()
     * @param  after function's result type
     * @return combined function
     */
    default  ThrowingBiFunction andThen(final ThrowingFunction after) {
        Objects.requireNonNull(after);

        return (arg1, arg2) -> after.apply(apply(arg1, arg2));
    }

    default BiFunction unchecked() {
        return (arg1, arg2) -> {
            try {
                return apply(arg1, arg2);
            } catch (final Throwable e) {
                throw new WrappedException(e);
            }
        };
    }

    default BiFunction> lift() {
        return (arg1, arg2) -> {
            try {
                return Optional.of(apply(arg1, arg2));
            } catch (Throwable e) {
                return Optional.empty();
            }
        };
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy