“Missing return statement” within if / for / while

后端 未结 7 969
粉色の甜心
粉色の甜心 2020-11-22 02:02

I have a question regarding return statements used within if() while() or for() statements. As you can see in the following method, it

7条回答
  •  清酒与你
    2020-11-22 02:12

    That is illegal syntax. It is not an optional thing for you to return a variable. You MUST return a variable of the type you specify in your method.

    public String myMethod()
    {
        if(condition)
        {
           return x;
        }
    }
    

    You are effectively saying, I promise any class can use this method(public) and I promise it will always return a String(String).

    Then you are saying IF my condition is true I will return x. Well that is too bad, there is no IF in your promise. You promised that myMethod will ALWAYS return a String. Even if your condition is ALWAYS true the compiler has to assume that there is a possibility of it being false. Therefore you always need to put a return at the end of your non-void method outside of any conditions JUST IN CASE all of your conditions fail.

    public String myMethod()
    {
        if(condition)
        {
           return x;
        }
      return ""; //or whatever the default behavior will be if all of your conditions fail to return.
    }
    

提交回复
热议问题