package eu.dnetlib.miscutils.functional;

import java.lang.reflect.Constructor;

/**
 * Functional helpers.
 * 
 * @author marko
 * 
 */
public class Functional {
	/**
	 * Given a class and a constructor type, return a unary function which invokes the constructor of that class.
	 * 
	 * @param <A>
	 * @param <B>
	 * @param clazz
	 * @param argumentType
	 * @return
	 */
	static public <A, B> UnaryFunction<A, B> construct(final Class<? extends A> clazz, final Class<? extends B> argumentType) {
		return new UnaryFunction<A, B>() {
			@Override
			public A evaluate(final B arg) {
				try {
					final Constructor<? extends A> constructor = clazz.getConstructor(new Class[] { argumentType });
					return constructor.newInstance(arg);
				} catch (Exception e) {
					throw new IllegalArgumentException(e);
				}
			}
		};
	}
}
