Click here to Skip to main content
15,891,423 members
Articles / Programming Languages / Java

Functional Java

Rate me:
Please Sign up or sign in to vote.
4.11/5 (6 votes)
7 Dec 2010CPOL8 min read 39.7K   284   14  
Functional programming with functors and object streams in Java.
package swensen.functional;

import java.util.concurrent.Callable;

/**
 * Provides compatibility between Func0 and Callable.
 * @author Stephen Swensen
 * @param <T> the functor return type.
 */
public abstract class CallableFunc<T> implements Func0<T>, Callable<T> {
    /**
     * Create a CallableFunc from a Func0.
     * @param <T> the functor return type.
     * @param func the Func0 to wrap, not null.
     * @return a new CallableFunc.
     */
    public static <T> CallableFunc<T> from(final Func0<? extends T> func)
    {
        if(func == null)
            throw new NullPointerException("func");

        return new CallableFunc<T>() {
            public T call() {
                return func.call();
            }
        };
    }

    /**
     * Create a CallabeFunc from a Callable. If callable throws an Exception, it is caught and rethrown wrapped as a RuntimeException.
     * @param <T> the functor return type.
     * @param callable the Callable to wrap, not null.
     * @return a new CallableFunc.
     */
    public static <T> CallableFunc<T> from(final Callable<? extends T> callable)
    {
        if(callable == null)
            throw new NullPointerException("callable");

        return new CallableFunc<T>() {
            public T call() {
                try {
                    return callable.call();
                }
                catch (Exception e){
                    throw new RuntimeException(e);
                }
            }
        };
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
I'm developing Unquote, a library for writing unit test assertions as F# quoted expressions: http://code.google.com/p/unquote/

I am working through Project Euler with F#: http://projecteulerfun.blogspot.com/

I participate in Stack Overflow: http://stackoverflow.com/users/236255/stephen-swensen

Comments and Discussions