I have list of methods which has Supplier<T>
arguments for returning default values of different types. However, in some cases I need to throw exception(unchecked) instead of values.
Currently, I have to pass the lambda for each function definition but I would like to create supplier instance for throwing the exception and re-use it in all function definition.
I have following code:
public static void main(String[] args)
{
testInt("Key1", 10, () -> 99);
testInt("Key2", -19, () -> 0);
testInt("Key3", null, () -> {
throw new UnsupportedOperationException(); //repetition
});
testBoolean("Key4", true, () -> Boolean.FALSE);
testBoolean("Key5", null, () -> {
throw new UnsupportedOperationException();//repetition
});
}
static void testInt(String key, Integer value, Supplier<Integer> defaultValue)
{
if (value != null)
System.out.printf("Key : %s, Value : %d" + key, value);
else
System.out.printf("Key : %s, Value : %d" + key, defaultValue.get());
}
static void testBoolean(String key, Boolean value, Supplier<Boolean> defaultValue)
{
if (value != null)
System.out.printf("Key : %s, Value : %d" + key, value);
else
System.out.printf("Key : %s, Value : %d" + key, defaultValue.get());
}
But I am looking to do something like :
final static Supplier<?> NO_VALUE_FOUND = () -> {
throw new UnsupportedOperationException();
};
testInt("Key3", null, NO_VALUE_FOUND);
testBoolean("Key5", null,NO_VALUE_FOUND);
Appreciate any help on this. Thanks.
Similar to @jon-hanson's answer, you can define a method which returns the lambda directly, with no cast needed:
private <T> Supplier<T> noValueFound() {
return () -> {
throw new UnsupportedOperationException();
};
}
Use a method to convert the NO_VALUE_FOUND value to the appropriate type:
static <T> Supplier<T> NO_VALUE_FOUND() {
return (Supplier<T>) NO_VALUE_FOUND;
}
public static void main(String[] args) {
testInt("Key3", null, NO_VALUE_FOUND());
testBoolean("Key5", null,NO_VALUE_FOUND());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With