How come lambda expressions are objects in Java?

Viewed 160

How are lambda expressions objects in Java? How can lambda expressions, which are a part of functional programming, be implemented in Java, which is an object-oriented language? What Java concepts do I need to understand lambda expressions?

3 Answers

You need to understand few things:

1) Functional interface

  • interface which has only one public method
public interface Runnable{
    void run();
}
  • this is example of functional interface, it can have different kinds of methods such as int processNumber(int number)
  • just remember there can be only one method (one not implemented method, defaults do not count)

2) Using functional interface

  • you can implement your functional interface in your class let's say MyRunnable
public class MyRunnable implements Runnable{
    public void run(){
        System.out.println("Hello world");
    }
}
  • than you can pass your MyRunnable class in another methods its just normal object
public class MyClass{
    public void myMethod(Runnable runnable){
        runnable.run();
    }
}
  • this would print "Hello world"
public static void main{
    MyClass myClass = new MyClass();
    myClass.myMethod(new MyRunnable());
}

3) What lambda is doing

  • so what lambda let you do is to create anonymous implementation of interface
public static void main{
    MyClass myClass = new MyClass();
    myClass.myMethod(() -> System.out.println("Hello my world"));
}
  • this would print "Hello my world"
  • you are just creating anonymous implementation of Runnable and passing it to MyMethod
  • it is just syntactic sugar for this
public static void main{
    MyClass myClass = new MyClass();
    myClass.myMethod(new Runnable{
        public void run(){
            System.out.println("Hello my world");
        });
}

Java is a Object Oriented Language. But some features from functional languages are also available in java like lambda

lambda is basically an object that acts like a function. documentation : https://docs.oracle.com/javase/8/docs/api/java/util/function/Function.html

as usual a function has an input and an output

inputs in functions : referred as T(as in take)

outputs in function : referred as R(as in return)

structure of declaration : Function<T,R> var_name = input_variables -> output_expression

example : Function<Double,Double> Sigmoid = x->(1/( 1 + Math.pow(Math.E,(-1*x))));

or there is another way(also known as method reference)

this is actually accessing the method under the hood

Function<T,R> var_name = class_name :: method_name

example : Function<Double,Double>Tanh = Math::tanh

Using a function

To use an function you just need to call the apply(T t) method of the function class

example : double num = sigmoid.apply(0)

Related