How do I pass a lambda function as a parameter?

0

I'm doing a college job where I have to develop a calculator with Java. I'm trying to figure out how to pass lambda functions as a parameter so that it's possible to put these functions into a list, so the calculator would have several options to perform operations.

I know there are other ways of running the same idea using different methods, but I'd like to do so. The problem is that I do not know which object to use to receive lambda as a parameter by function. I chose lambda instead of Runnable and Callable since in addition lambda can return values, it is easier for a new developer to implement a new operation on the calculator, since it only needs to add the lambda equivalent to the operation and some more information.

    
asked by anonymous 12.10.2018 / 04:59

1 answer

0

A lambda function is nothing more than an implementation of a functional interface. Knowing this let's go to the answer, following the information you gave in my main class will have a List object to contain the list of functions.

The functional inferface referring to the lamdas would look like this:

@FunctionalInterface
public interface Lambda<T> {

  T executarFuncao(T num1, T num2);
}

The class that would use this interface (in my case the class Main) would look like this:

public class Main {

    //  Definindo a lista de Lambdas
    private static final List<Lambda> listaLambdas = new ArrayList<>();

    public static void main(String[] args) {

        //  Criando uma função para soma
        Lambda<Double> somar = (num1, num2) -> num1 + num2;

        //  Criando uma função para subtração
        Lambda<Double> subtrair = (num1, num2) -> num1 - num2;

        //  Adicionando funções a lista de Lambdas
        listaLambdas.add(somar);
        listaLambdas.add(subtrair);

        //  Um exemplo de execução
        listaLambdas.forEach(funcao -> {
            System.out.println(
                    funcao.executarFuncao(1.0, 2.0)
            );
        });

    }
}

I recommend reading additional functional interfaces and lambdas if you want to go deeper into these features:

What are Functional Interfaces?

What is use of Functional Interface in Java 8 ?

    
12.10.2018 / 06:24