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
}
Pankaj
  • 3,512
  • 16
  • 49
  • 83

3 Answers3

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.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • @PravatPanda in fact, returning a `null` is a design matter as discussed [here](http://stackoverflow.com/q/271526/1065197). 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. – Luiggi Mendoza Jun 21 '13 at 22:11
  • @LuiggiMendoza. True. Should have added this earlier. Thnx :) – Rohit Jain Jun 21 '13 at 22:14
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.

arshajii
  • 127,459
  • 24
  • 238
  • 287
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.

kosa
  • 65,990
  • 13
  • 130
  • 167