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

se.l4.commons.io.IOFunction Maven / Gradle / Ivy

There is a newer version: 1.2.2
Show newest version
package se.l4.commons.io;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.Objects;
import java.util.function.Function;

/**
 * {@link Function} that can throw {@link IOException}.
 *
 * @author Andreas Holstenson
 *
 * @param 
 * @param 
 */
@FunctionalInterface
public interface IOFunction
{
	/**
	 * Apply this function to the given input.
	 *
	 * @param t
	 *   input to apply to
	 * @return
	 *   result
	 */
	R apply(T t)
		throws IOException;

	/**
	 * Compose the before function with this one. The before function will be
	 * applied first followed by this one.
	 *
	 * @param before
	 *   the function to apply before this one
	 * @return
	 *   composed function
	 */
	default  IOFunction compose(IOFunction before)
	{
		Objects.requireNonNull(before);
		return t -> apply(before.apply(t));
	}

	/**
	 * Compose the before function with this one. The before function will be
	 * applied first followed by this one.
	 *
	 * @param before
	 *   the function to apply before this one
	 * @return
	 *   composed function
	 */
	default  IOFunction compose(Function before)
	{
		Objects.requireNonNull(before);
		return t -> apply(before.apply(t));
	}

	/**
	 * Compose this function with another one. This function will be applied
	 * first followed by the after function.
	 *
	 * @param after
	 *   the function to apply after this function
	 * @return
	 *   composed function
	 */
	default  IOFunction andThen(IOFunction after)
	{
		Objects.requireNonNull(after);
		return t -> after.apply(apply(t));
	}

	/**
	 * Compose this function with another one. This function will be applied
	 * first followed by the after function.
	 *
	 * @param after
	 *   the function to apply after this function
	 * @return
	 *   composed function
	 */
	default  IOFunction andThen(Function after)
	{
		Objects.requireNonNull(after);
		return t -> after.apply(apply(t));
	}

	/**
	 * Turn this {@link IoFunction} into a regular {@link Function}. The
	 * regular function will throw {@link UncheckedIOException} if this
	 * function raises an {@link IOException}.
	 *
	 * @return
	 *   function that invokes this one
	 */
	default Function toFunction()
	{
		return t -> {
			try
			{
				return apply(t);
			}
			catch(IOException e)
			{
				throw new UncheckedIOException(e);
			}
		};
	}

	/**
	 * Adapt a {@link Function} into a {@link IOFunction}.
	 *
	 * @param func
	 *   the function to adapt
	 * @return
	 *   {@link IOFunction} that runs the given regular {@link Function}
	 */
	static  IOFunction adapt(Function func)
	{
		return item -> func.apply(item);
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy