Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Generic Supplier to throw unchecked excpetion

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.

like image 432
Chota Bheem Avatar asked Dec 17 '22 19:12

Chota Bheem


2 Answers

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();
    };
}
like image 56
MikeFHay Avatar answered Dec 30 '22 10:12

MikeFHay


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());
}
like image 27
jon-hanson Avatar answered Dec 30 '22 10:12

jon-hanson