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

com.pivovarit.function.ThrowingIntFunction Maven / Gradle / Ivy

There is a newer version: 1.6.1
Show newest version
package com.pivovarit.function;

import com.pivovarit.function.exception.WrappedException;

import java.util.Optional;
import java.util.function.IntFunction;

import static com.pivovarit.function.SneakyThrowUtil.sneakyThrow;
import static java.util.Objects.requireNonNull;

/**
 * Functional interface mirroring {@link IntFunction} for primitive ints from the java.util.function package.
 * This allows wrapping a exceptions in a runtime exception: {@link WrappedException}
 * 

* As this adheres to the {@link IntFunction} interface, compose and andThen (as you might be familiar with from * {@link java.util.function.Function} are not available. * * @param the type of the result of the function * @param the type of the thrown checked exception */ @FunctionalInterface public interface ThrowingIntFunction { R apply(int i) throws E; default IntFunction uncheck() { return t -> { try { return apply(t); } catch (final Exception e) { throw new WrappedException(e); } }; } static IntFunction unchecked(final ThrowingIntFunction f) { return requireNonNull(f).uncheck(); } /** * @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 IntFunction> lifted(final ThrowingIntFunction f) { return requireNonNull(f).lift(); } static IntFunction sneaky(ThrowingIntFunction function) { requireNonNull(function); return t -> { try { return function.apply(t); } catch (final Exception ex) { return sneakyThrow(ex); } }; } default IntFunction> lift() { return t -> { try { return Optional.ofNullable(apply(t)); } catch (final Exception e) { return Optional.empty(); } }; } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy