Solved

Returning a Function?

Posted on 2000-03-27
10
265 Views
Last Modified: 2006-11-17
Can I return a function in Java from another function? You can do this in Scheme - a dialect of LISP...
0
Comment
Question by:streaks619
  • 2
  • 2
  • 2
  • +4
10 Comments
 
LVL 1

Expert Comment

by:filipecorreia
Comment Utility
If I correctly understood what you're asking:
OF COURSE YOU CAN!!!

But you'd better explain it better...
:)




Filipe Correia
0
 
LVL 19

Expert Comment

by:Jim Cakalic
Comment Utility
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
0
 
LVL 8

Expert Comment

by:diakov
Comment Utility
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?

Cheers,
  Nik
0
 
LVL 8

Expert Comment

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

Cheers,
  Nik
0
 
LVL 16

Expert Comment

by:heyhey_
Comment Utility
> 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.
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 1

Expert Comment

by:yogeshr
Comment Utility
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)
{
   B();
}
else
{
   System.out.println("in the else loop");
    return false;
}
}

public boolean B() throws Exception
{
............
............
............
return true;
}
Still pls describe the question specifically .
0
 
LVL 5

Expert Comment

by:Jod
Comment Utility
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.

0
 
LVL 5

Expert Comment

by:Jod
Comment Utility
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.
0
 
LVL 2

Accepted Solution

by:
AlexJ030200 earned 100 total points
Comment Utility
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:
http://www.math.luc.edu/pizza/gj/

That's all.
0
 
LVL 2

Expert Comment

by:AlexJ030200
Comment Utility
oups, I said interface when I meant abstract class.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
This video teaches viewers about errors in exception handling.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now