I have an array of methods which can be called and need a boolean as a parameter. I have tried this:
public class Example {
public Function<Boolean, Integer> getFunctions(boolean t) {
return new Function[] {
this::magicNumber
};
}
public int magicNumber(boolean t) {
return (t) ? new Random().nextInt(11) : 0;
}
}
But then the compiler returns an error message with the message
Incompatible types: invalid method reference
Incompatible types: Object cannot be converted to boolean
The example above however can work by storing the Function in a variable and returning that, however I don't find this clean code and it's redundant.
public class Example {
public Function<Boolean, Integer> getFunctions(boolean t) {
Function<Boolean, Integer> f = this::magicNumber;
return new Function[] {
f
};
}
public int magicNumber(boolean t) {
return (t) ? new Random().nextInt(11) : 0;
}
}
Is there any way to shorten the code above like in the example in the beginning?
EDIT
As a commenter requested, I will give a short example of how I used Supplier in a previous project. I return them in an array to return objects. The problem is that this project depends on having a parameter.
public Supplier<T>[] getRecipes()
{
return new Supplier[] {
this::anchovyRule,
this::codRule,
this::herringRule,
this::lobsterRule,
this::mackerelRule,
this::pikeRule,
this::salmonRule,
this::sardineRule,
this::shrimpRule,
this::troutRule,
this::tunaRule
};
}