Why cannot I return void from a void function

Son of Stackoverflow :

Why does this code work

void hello()
{
hello();
return;
}

while this does not

void hello(){return hello();}

Error:

java.java:13: error: incompatible types: unexpected return value
return hello();

(Please ignore the logical error)

The main question: Why cannot we return void to a void function?

Does Java by any means provide support another type of void, maybe a wrapper class called Void?

Andrew Tobilko :

There is a way

class A {
  Void a() {
    // ...
    return a();
  }
}

but java.lang.Void is an uninstantiable representation of the void type meaning you can't make instances out of it (and, sensibly, you aren't supposed to). Eventually, you would need to return a value, it could be a null - the only "legit" one I can think of.

It has applications with generics and the Reflection API, but I doubt it being used here for the purpose of making a recursive method fancier (?).

class A {
  Consumer<String> a() {
    return System.out::println;
  }
}

You might want to return an instance of a function that returns void. Then, a functional interface java.util.function.Consumer might be a good fit.

Actually, it could be any interface of the kind that would suit you best. For instance,

class A {
  Runnable a() {
    // ...
    return () -> a();
  }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=396292&siteId=1