代码之家  ›  专栏  ›  技术社区  ›  Son of Stackoverflow Nagendra Nigade

为什么不能从void函数返回void

  •  0
  • Son of Stackoverflow Nagendra Nigade  · 技术社区  · 6 年前

    为什么这个代码有效

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

    void hello(){return hello();}
    

    错误:

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

    主要问题是:为什么我们不能将void返回到void函数?

    Java以任何方式提供了对另一种类型的 void Void ?

    4 回复  |  直到 6 年前
        1
  •  1
  •   Andrew    6 年前

    有办法的

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

    但是 java.lang.Void void null -我能想到的唯一“合法”的。

    它的应用程序 generics and the Reflection API

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

    您可能希望返回返回 无效 java.util.function.Consumer

    实际上,它可以是最适合您的任何接口。例如,

    class A {
      Runnable a() {
        // ...
        return () -> a();
      }
    }
    
        2
  •  1
  •   Antoniossss    6 年前

    因为 void 函数不返回值,因此不能 return 什么都行。 return; 只是“完成方法执行”或“退出方法”,而不是“不返回任何内容”;

        3
  •  1
  •   Usagi Miyamoto    6 年前

    对于单行程序,请尝试以下操作:

    void hello() { hello(); }
    

    void hello() { return hello(); }
    
        4
  •  1
  •   Arvind Kumar Avinash    6 年前

    带返回类型 void ,只能返回返回类型, Void ,您可以返回 null 例如

    public class Main {
        public static void main(String[] args) {
            hello();
        }
    
        static Void hello() {
            System.out.println("Hello");
            return null;
        }
    }
    

    输出:

    Hello
    

    你可以找到更多的 无效 https://www.baeldung.com/java-void-type

        5
  •  1
  •   Baraa    6 年前

    因为当一个方法的返回值 void 无效 它自己。

    return x; 指示控件正在离开方法,并且其结果是x的值。

    return; 指示控件离开方法而没有结果。

    void fun () {return void;} // does not work
    

    请参考这个 answer