2

How lambda expressions in Java 8 enable functional programming? Because lambda expression type is represented as interface and which is object-oriented class type.

How normal method call differs from lambda expression statement?

3 Answers 3

3

Lambda does not enable functional programming. It allows you to process data in more functional style.

Java is an OOP language, where first-class citizens are objects, not functions. Therefore, even when you declare a lambda expression you have to assign it to some Functional Interface, which as you said is an object oriented class type.

However, in Java 8 you can use a lambda expression, which is an anonymous function, like a first-class citizen to process data in a functional style. E.g. you can pass an anonymous function as a method parameter.

accounts.stream()
        .map(account -> account.getEmail())
        .filter(email -> email.endsWith("gmail.com"))

This is a valid Java 8 code, where you pass as method arguments, not values, but functions. Of course, under the hood these lambdas become instances of classes that implement functional interface Function<Account,String>, and Predicate<String> accordingly, but still it allows you to process data in more functional style than in old Java versions.

The whole idea of processing data in a functional style involves also Streams, Functional Interfaces, and Method Reference, so you should consider them all when you think about functional programming in Java.

Sign up to request clarification or add additional context in comments.

Comments

3

In the Functional Programming world, functions are objects too and can be treated as traditional objects.

Lambdas itself are simply behaviours without name handles. If you write x -> x + 1, you just created a value that represents an incrementation (or a concatenation of two strings).

This option allows to not only compose classical objects together but also to compose behaviours/actions - which is critical for Functional Programming which utilizes declarative programming a lot - in order to be able to achieve this, you need to be able to pass a behaviour in some way.

But, the presence of Lambda Expressions does not make any language functional automatically - there is much more to it, e.g. Immutability, Algebraic Data Types, lack of side-effects, functors, data types... and so on.


So, the relation between a lambda and a method is somehow similar to a relation between an anonymous value and a class field.

Comments

1

Lets imagine pure OOP without class fields, setters and getters. only classes and methods... and we got a pure functional programming. As fact, OOP - extends Functional Programming by adding state. State adds reusability, save the time, by storing input parameters, incoming from class constructor.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.