javacasting

Safe to Cast when method depends on higher level interface


Consider the code below:

public class DummySupplier<T> implements Supplier<T> {

    private final Supplier<T> supplier;

    public static<T> DummySupplier<T> of(Supplier<T> supplier) {
        return new DummySupplier<>(supplier);  
    }

    private DummySupplier(Supplier<T> supplier) {
        this.supplier = supplier;
    }

    @Override
    public T get() {
        return supplier.get();
    }
}

public class Main {

    public static void main(String[] args) {
        DummySupplier<String> stringSupplier = DummySupplier.of(() -> "Hello, World!");

        // Calling function with multiple arguments
        processSuppliers(42, "Test", stringSupplier, 3.14);
    }

    //Method getting Object... args
    public static void processSuppliers(Object... args) {
        for (Object arg : args) {
            Supplier<?> supplier;
            if (arg instanceof Supplier<?>) {
                arg = arg.get();
            }

            System.out.println("Supplied: " + arg.toString());
        }
    }
}

Will it be safe just to typecast the input argment to Supplier<T>.of to DummySupplier<T> rather than creating a new object of DummySupplier? The other functions which are using depends only on Supplier, not on DummySupplier.

Why DummySupplier? Because other methods are accepting Object ...args. Here, I want to pass Supplier. Now, that method is taking care of Supplier<?>. Using Supplier lambda, I cannot pass as Object as an argument.


Solution

  • It seems to me like you don't need a DummySupplier<> at all. Just change your main method to:

    public static void main(String[] args) {
        Supplier<String> stringSupplier = () -> "Hello, World!";
        // Calling function with multiple arguments
        processSuppliers(42, "Test", stringSupplier, 3.14);
    }
    

    That works fine. You were already depending on the conversion from a lambda expression to a Supplier<> - there's no need to create another implementation to wrap that.