0

I've the below method which expects a return type as SomeObject. mapData() function returns SomeObject. I want to come out from the loop as soon as one condition gets satisfied. I'm getting compilation error due to no return type found. Can you please point out the issue with my condition ?

 public static SomeObject mapper(List<String> mylist) {
    Iterator iter = mylist.iterator();
    while (iter.hasNext()) {
        Object[] result = (Object[]) iter.next();
            if (condition){
                //dosomething
                return mapData(abc);
            }else if (condition) {
                //dosomething
                return mapData(def);
            }else {
                //dosomething
                return mapData(ghi);
            }
    }
  // Get compilation error due to no return type at this position
}
1
  • 3
    You can add a return null; after the while loop. Geez... Now looking how people crawl for rep. Commented Jun 21, 2013 at 22:04

3 Answers 3

4

Imagine what happens when your while loop never executes? This will happen if your list is empty. In that case, your method would not return anything, thus the error.

Just add a return statement:

return null;

after your while loop. Or return some default instance of SomeObject, if you haven't done the null check for the value returned by this method.

Sign up to request clarification or add additional context in comments.

2 Comments

@PravatPanda in fact, returning a null is a design matter as discussed here. IMO I would prefer to evaluate if the method should return null or not instead of just setting a return null at the bottom. And if you prefer to not return anything at all after the while loop, you can throw an exception (or a RuntimeException if want to be silent) and handle the exception in the caller as explained in arshajii answer which can lead to another design.
@LuiggiMendoza. True. Should have added this earlier. Thnx :)
3

The compiler requires that all possible code paths either

  • return a value
  • throw an exception

You should do whichever makes more sense in the context of your program, in your case that means adding one of these statements to the end of your method.

Comments

0

Add return null; (or) relevant return statement at the end.

If none of the conditions satisfied in your while loop, then this will be returned.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.