Supplier or not a supplier

750 views Asked by At

I am new to java 8 and I have this question

private Supplier<MissingAttribute> getExceptionSupplier(final String message) {
return () -> new MissingAttribute(message);        
    }

A team member of mine said taking in message object makes it no longer a supplier but a function but another team member said this is still a supplier (a get function). The message in the function is predefined

I am confused as to what is right.

public class MissingAttribute extends Exception {
public MissingAttribute(String message, Exception cause) {
super(message + " : " + cause.getMessage(), cause);
}
public MissingAttribute(String message) { 
super(message); 
} 
.
.
. 

I did research online, but I am still not sure of the answer. Any insights on this are appreciated!!

2

There are 2 answers

0
Vincent Passau On BEST ANSWER

Your method returns technically a Supplier, i.e. an Object that receives no parameters and that returns something.

But in the idea, it looks like a Function because you provide a parameter to the method and the supplier it creates is dependent of this parameter.

Nevertheless it is still a Supplier because once it is created you will always have the same behaviour at each call. Note that it's perfectly standard for a Supplier to take an external constant into account.

In conclusion, following the use of this supplier in the calling code, it could be refactored as a Function or it makes sense to keep this method that creates a Supplier with a parameter.

0
Deep On

Your function getExceptionSupplier returns a Supplier taking a String as it's argument. Supplier here is not taking any object as it's input. You function here taking a String instead. You are confusing with ordinary function & Function<T,U> Functional Interface which takes type T as input & produces type U as output.