How do I pass a lambda function as a parameter?

Asked

Viewed 443 times

0

I’m doing a college project where I have to develop a calculator with Java. I am trying to find a way to pass lambda functions as a parameter so that it is possible to put these functions inside a list, so the calculator would have several options of operations to be performed.

I know there are other ways to execute the same idea using different methods, but I would like to do so. The problem is that I don’t know which object to use to receive lambda as a function parameter. I chose lambda instead of lambda Runnable and Callable because lambda can return values, it is easier for a new developer to implement a new operation in the calculator, as it just needs to add lambda equivalent operation and some more information.

  • 1

    The ideal would be to show how it has at this time to be easier to understand its difficulties

1 answer

1

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

The functional inferface referring to the gills would be as follows:

@FunctionalInterface
public interface Lambda<T> {

  T executarFuncao(T num1, T num2);
}

The class that would use this interface (in my case the Main class) 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 as additional reading on functional interfaces and Ambdas if you want to deepen the functioning of these resources:

What are functional interfaces?

What is use of Functional Interface in Java 8?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.