Returning a Function?

Can I return a function in Java from another function? You can do this in Scheme - a dialect of LISP...
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

If I correctly understood what you're asking:

But you'd better explain it better...

Filipe Correia
Jim CakalicSenior Developer/ArchitectCommented:
Java does not allow returning a function pointer or invoking a method by pointer in the style of C/C++. I would need more details to understand whether it would be possible to emulate your experience with Scheme.

Before I go any further, I must say that there is usually a more OO way to accomplish the same task in Java. For example, the Strategy pattern encourages creating a family of encapsulated interchangeable algorithms when:

    1) many related classes differ only in their behavior. Strategies provide a way to configure a class with one of many behaviors.

    2) you need different variants of an algorithm. For example, you might define algorithms reflecting different space/time trade-offs. Strategies can be used when these variants are implemented as a class hierarchy of algorithms.

    3) an algorithm uses data that clients shouldn't know about. Use the Strategy pattern to avoid exposing complex, algorithm-specific data structures.

    4) a class defines many behaviors, and these appear as multiple conditional statements in its operations. Instead of many conditionals, move related conditional branches into their own Strategy class.

Situations in which you want to return functions or pointers can be solved by creating classes that encapsulate the behavior of the desired function and returning an object of that type. Using function pointers in C/C++, the signature for all the functions must be the same. Likewise, the method signature(s) of the strategy classes would be identical so that given an object of any of this family of classes, you could call one or more methods as needed by your application. You'd probably use an interface to further solidify this relationship.

Finally, there may be a less OO (in my opinion) solution possible using reflection. A Method provides information about and access to a single method on a reflected class or interface. The invoke method of this class allows you to invoke the method represented by the Method object on a specified object using specified parameters. Looking at it as I write this, it doesn't seem particularly elegant or straightforward a solution. But I felt it bore mentioning, as someone may comment on it later.

I'd be happy to add further comments if you care to describe or provide an example of how function passing/invocation works in Scheme.

Best regards,
Jim Cakalic
LISP is a language for functional  programming where objects are the functions itself. In Java, the functions are the methods of a class. Normally you need a object reference and the method name to call the methods. Through java reflection package, you can select and extract a Method definition and using the description about this methods, call it on a Object reference. The reflection package does not give much more than the normal approach, however, it gives you the freedom to use the base Objcet class as a type of the object reference, and call a method by specifying it either with Method reference or a String (you can find the method actually).

I remember there I saw somewhere a LISP implementation in Java. Are you interested?

Become a Microsoft Certified Solutions Expert

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

Another approach where you don't need the object reference is with static methods. But then, you need to specify the class anyway.

> Can I return a function in Java from another function?

1. you don't have functions in Java, so you can't return function :)
2. you can return several 'function's 'wrapped' in an Object that implements some specific interface.
Your question itself is not clear. Do you want to ask whether you can get the return value of a function from some other function? If that is it than it is possible to do it in Java.

You can do it as follow:-

public boolean A() throws Exception
if (true)
   System.out.println("in the else loop");
    return false;

public boolean B() throws Exception
return true;
Still pls describe the question specifically .
You cannot do this in Java directly - it is not the way that Java as an OO language works.

Lisp is a functional programming language so it allows this sort of functionality to solve problems in a recursive fashion by returning functions directly that are in turn invoked on lists of data items.

In Java you can approach your problem in two ways:

1) Return an object which contains the method you wish to invoke. Ideally make an interface with only one method signature in (that is, one description of a method - no implementation in interfaces).

You then implement this interface in every object you wish to return from your function. Then when you return your object from the function you have called you cast it to be of this interface type and return it.

All objects that implement this interface will then all look the same to the code that receives the object back from your function.

You then just invoke the method in the interface when you get the object back.

2) You could also try and do it in more complicated ways - my advice is don't bother unless you really need to.

If you explain why you need to do this there may be a more suitable workaround for you.

Here is the full details of how to do this as a tip from Javaworld...

Developers may be accustomed to passing function pointers that are invoked (that is, "called back") when something happens. Java's object-oriented model does not currently support method pointers, and thus seems to preclude using this comfortable mechanism. But all is not lost!

Java's support of interfaces provides a mechanism by which we can get the equivalent of callbacks. The trick is to define a simple interface that declares the method we wish to be invoked.

For example, suppose we want to be notified when an event happens. We can define an interface:

public interface InterestingEvent
    // This is just a regular method so it can return something or
    // take arguments if you like.
    public void interestingEvent ();

This gives us a grip on any objects of classes that implement the interface. So, we need not concern ourselves with any other extraneous type information. This is much nicer than hacking trampoline C functions that use the data field of widgets to hold an object pointer when using C++ code with Motif.

The class that will signal the event needs to expect objects that implement the InterestingEvent interface and then invoke the interestingEvent() method as appropriate.

public class EventNotifier
    private InterestingEvent ie;
    private boolean somethingHappened;

    public EventNotifier (InterestingEvent event)
 // Save the event object for later use.
 ie = event;

 // Nothing to report yet.
 somethingHappened = false;


    public void doWork ()
 // Check the predicate, which is set elsewhere.
 if (somethingHappened)
     // Signal the even by invoking the interface's method.
     ie.interestingEvent ();

    // ...

In that example, I used the somethingHappened predicate to track whether or not the event should be triggered. In many instances, the very fact that the method was called is enough to warrant signaling the interestingEvent().

The code that wishes to receive the event notification must implement the InterestingEvent interface and just pass a reference to itself to the event notifier.

public class CallMe implements InterestingEvent
    private EventNotifier en;

    public CallMe ()
 // Create the event notifier and pass ourself to it.
 en = new EventNotifier (this);

    // Define the actual handler for the event.
    public void interestingEvent ()
 // Wow! Something really interesting must have occurred!
 // Do something...


That's all there is to it.
Hi, as previously explained in other answers, you don't have functions in Java, but instead, you have inner classes that allow you to do everything you can do with functional languages. Let me give you an example with the following interface:

public abstract class Lambda {

  public abstract Object fnc(Object[] args);

  public static Object apply(Object function, Object[] args) throws Exception {

    if (!(function instanceof Lambda)) throw new Exception("Not a Lambda Object");
    return ((Lambda)function).fnc(args);


Whenever you need to produce a functional value, you have to write:

new Lambda() {

  public Object fnc(Object[] args) {
    // Here you insert the body of your function


If you are a Lisp/Scheme user, here types won't border you. If you prefer the ML or Haskel typed flavor of functional languages then the elaboration has to be more complicated. See for instance the Generic Java efforts at:

That's all.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
oups, I said interface when I meant abstract class.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.