Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is lambda expression only applicable for functional interface?

Tags:

java

java-8

I have just started learning java 8. There I read that lambda expression can only be applied to functional interfaces. But below code, I see from a java site. Here it is using MathOperation class and referring its methods using lambda expression, not referring to any method of a functional interface. If someone helps me understand it, it would be great.

package com.jcg.java;

import java.util.function.BiFunction;

class MathOperation {

    /**** Addition ****/
    public int add(int a, int b) {
        return a + b;
    }

    /**** Subtraction ****/
    public int sub(int a, int b) {
        return a - b;
    }
}

/***** Reference To An Instance Method Of A Particular Object *****/
public class MethodReferenceEx2 {

    public static void main(String[] args) {

        MathOperation op = new MathOperation();

        /**** Using Lambda Expression ****/
        System.out.println("--------------------Using Lambda Expression----------------------");
        BiFunction<Integer, Integer, Integer> add1 = (a, b) -> op.add(a, b);
        System.out.println("Addtion = " + add1.apply(4, 5));

        BiFunction<Integer, Integer, Integer> sub1 = (a, b) -> op.sub(a, b);
        System.out.println("Subtraction = " + sub1.apply(58, 5));

        /**** Using Method Reference ****/
        System.out.println("\n---------------------Using Method Reference---------------------");
        BiFunction<Integer, Integer, Integer> add2 = op::add;
        System.out.println("Addtion = " + add2.apply(4, 5));

        BiFunction<Integer, Integer, Integer> sub2 = op::sub;
        System.out.println("Subtraction = " + sub2.apply(58, 5));
    }
}
like image 753
user1988 Avatar asked Aug 07 '26 21:08

user1988


1 Answers

Here it is using MathOperation class and referring its methods using lambda expression, not referring to any method of a functional interface.

No, all the lambda expressions in this code implement the BiFunction<Integer, Integer, Integer> function interface.

The body of the lambda expressions is allowed to call methods of the MathOperation class. It doesn't have to refer only to methods of a functional interface.

When you wish to execute the method of the functional interface instance implemented by the lambda expression, you call the functional interface's method, as in sub2.apply(58, 5).

like image 175
Eran Avatar answered Aug 09 '26 09:08

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!