Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Missing return value on Void method?

Tags:

java

generics

The following code gives me compile-time errors: missing return value and missing return statement, what value would I return for this Void Type?

final SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
    @Override
    protected Void doInBackground() throws Exception {
        // some code
        if (something) {
            return;
        }
    }
}
like image 761
HericDenis Avatar asked Dec 06 '12 17:12

HericDenis


People also ask

Can you do return on void method?

A void function cannot return any values. But we can use the return statement. It indicates that the function is terminated. It increases the readability of code.

Does a void method always return a value?

Any method declared void doesn't return a value. It does not need to contain a return statement, but it may do so.

What happens when you return in a void method?

It exits the function and returns nothing.


2 Answers

Void is not void, change it to void type if you don't want to return anything.

Void is a class, void is type.

/**
 * The {@code Void} class is an uninstantiable placeholder class to hold a
 * reference to the {@code Class} object representing the Java keyword
 * void.
 *
 * @author  unascribed
 * @since   JDK1.1
 */

If you want Void, then you need to add return statement at end.

Example:

protected Void doInBackground() throws Exception {
    // some code
    if (something) {
       return null;
    }
    return null;
}
like image 136
kosa Avatar answered Sep 27 '22 19:09

kosa


Check this. It asks to return Void with captital "V" not with simple void

final SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
    @Override
    protected Void doInBackground() throws Exception {
        // my code here
        return null;
    }
}
like image 20
someone Avatar answered Sep 27 '22 19:09

someone