What did Java programmers do before Java 8 if they wanted to pass a function?

Please be careful with me.

I heard that Java 8 introduced lambda. But before that, if you want to pass a function, say, as an argument, what did you do?

One way I can imagine is to create a single method interface as follows:

public interface ISingleMethodInterface
{
  bool Really(int n);
}

public bool GimmeFunction(ISingleMethodInterface interface, int n)
{
  return interface.Really(n);
}

But this is a very limited use of functions as first-class citizens, because:

  • You can do nothing but execute this function or pass this object to another method. With lambdas you can compose. E.g. you can undo this lambda like this:

    public bool GimmeLambdaAndIWillComputeItsInverse(Func<int, bool> predicate, int n)
    {
      return !predicate(n);
    }
    
  • You cannot return lambda or its derivatives. I mean, you can return only the same object:

    // I know Java doesn't have Tuples but let forget that for now
    public Tuple GimmeFunction(ISingleMethodInterface interface, int n)
    {
      return new Tuple { Item1 = interface, Item2 = n };
    }
    

    With lambdas, you can return derivatives like this:

    public Func<int, bool> GetInverseFunction(Func<int, bool> predicate, int n)
    {
      return n => !predicate(n);
    }
    

, , - ?

+4
2

. lambdas , Java lambdas - . , , . , .

+3

Java 8, , :

object.gimmeFunction(new SingleMethodInterface(){
    @Override public bool really(int n){
        return n=="really".hashCode();
    }
});

(. Comparator, Runnable, ActionListener), , , Java 8 lambdas, :

object.gimmeFunction(n->n=="really".hashCode());

, Java- . , , - .

0

Source: https://habr.com/ru/post/1648114/


All Articles