tags:

views:

96

answers:

3

What are Java's equivalents of Func and Action?

I mean, instead of writing this on my own:

public interface Func<TInput, TResult>
{
    TResult call(TInput target) throws Exception;
}
public interface Action<T>
{
    void call(T target) throws Exception;
}
+2  A: 

There really are no equivalents for those. You can create anonymous inner classes in Java, but there tends to be specific interfaces rather than such generic ones like Func and Action.

AgileJon
+3  A: 

Java doesn't have the concept of delegates. For a workaround approach, please see A Java Programmer Looks at C# Delegates:

While C# has a set of capabilities similar to Java, it has added several new and interesting features. Delegation is the ability to treat a method as a first-class object. A C# delegate is used where Java developers would use an interface with a single method. In this article, the use of delegates in C# is discussed, and code is presented for a Java Delegate object that can perform a similar function. Download the source code here.

Andrew Hare
+2  A: 

Callable interface is similar to Func.

Runnable interface is similar to Action.

In general, Java uses anonymous inner classes as a replacement for C# delegates. For example this is how you add code to react to button press in GUI:

button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) { 
          ...//code that reacts to the action... 
      }
});
Gregory Mostizky