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

com.pivovarit.function.ThrowingFunction 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 com.pivovarit.function;

import com.pivovarit.function.exception.WrappedException;

import java.util.Optional;
import java.util.function.Function;

import static java.util.Objects.requireNonNull;

/**
 * Represents a function that accepts one argument and returns a value;
 * Function might throw a checked exception instance.
 *
 * @param  the type of the input to the function
 * @param  the type of the result of the function
 * @param  the type of the thrown checked exception
 * @author Grzegorz Piwowarek
 */
@FunctionalInterface
public interface ThrowingFunction {
    R apply(T arg) throws E;

    /**
     * @return a Function that returns the result of the given function as an Optional instance.
     * In case of a failure, empty Optional is returned
     */
    static  Function> lifted(final ThrowingFunction f) {
        return requireNonNull(f).lift();
    }

    static  Function unchecked(final ThrowingFunction f) {
        return requireNonNull(f).uncheck();
    }

    static  Function sneaky(ThrowingFunction function) {
        requireNonNull(function);
        return t -> {
            try {
                return function.apply(t);
            } catch (final Exception ex) {
                return SneakyThrowUtil.sneakyThrow(ex);
            }
        };
    }

    default  ThrowingFunction compose(final ThrowingFunction before) {
        requireNonNull(before);
        return v -> apply(before.apply(v));
    }

    default  ThrowingFunction andThen(final ThrowingFunction after) {
        requireNonNull(after);
        return t -> after.apply(apply(t));
    }

    default Function> lift() {
        return t -> {
            try {
                return Optional.ofNullable(apply(t));
            } catch (final Exception e) {
                return Optional.empty();
            }
        };
    }

    default Function uncheck() {
        return t -> {
            try {
                return apply(t);
            } catch (final Exception e) {
                throw new WrappedException(e);
            }
        };
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy