JFreeman
JFreeman

Reputation: 1004

Functional programming, objects that act as functions but don't return a value

I am trying to do some functional programming with java.

Function Objects takes one value and returns one value. Method takes no arguments.

Is there a default Object which takes one argument and returns nothings? Or should I create my own?

NewObject<String> stopListAdd =
            line -> stopList.add(xxx);

If I were to construct my own is there any way better than extending the Function object and just dismissing its return value?

Upvotes: 0

Views: 358

Answers (2)

Antonio Di Stefano
Antonio Di Stefano

Reputation: 54

Sure, java uses functional interfaces to back the type behind lambdas. In short, when creating a lambda you are just implementing an interface with a single abstract method, called a functional interface. So if you want to create your functional types, you just need to create an interface with a single abstract method that matches your requirements, like in this case

void accept();

One side note, default methods can be added to a functional interface as they are in fact implemented already.

So, Function and other similar types are not the full extents of functional types in java, but rather a subset of commonly used, reusable and well-known functional interfaces that you don't have to redeclare each and every time.

Upvotes: 3

Adam Siemion
Adam Siemion

Reputation: 16039

java.util.function.Consumer accepts a single input argument and returns no result.

Upvotes: 2

Related Questions