Return different type of data from a method in java?

Ruchira Gayan Ranaweera picture Ruchira Gayan Ranaweera · Aug 9, 2013 · Viewed 130.1k times · Source
public static void main(String args[]) {
    myMethod(); // i am calling static method from main()
 }

.

public static ? myMethod(){ // ? = what should be the return type
    return value;// is String
    return index;// is int
}

myMethod() will return String and int value. So take these returning values from main() i came up with following solution.

create a class call ReturningValues

public class ReturningValues {
private String value;
private int index;

// getters and setters here
}

and change myMethod() as follows.

 public static ReturningValues myMethod() {
    ReturningValues rv = new ReturningValues();
    rv.setValue("value");
    rv.setIndex(12);
    return rv;
}

Now my question,is there any easier way to achieve this??

Answer

Wendel picture Wendel · Sep 9, 2015

I create various return types using enum. It doesn't defined automatically. That implementation look like factory pattern.

public  enum  SmartReturn {

    IntegerType, DoubleType;

    @SuppressWarnings("unchecked")
    public <T> T comeback(String value) {
        switch (this) {
            case IntegerType:
                return (T) Integer.valueOf(value);
            case DoubleType:
                return (T) Double.valueOf(value);
            default:
                return null;
        }
    }
}

Unit Test:

public class MultipleReturnTypeTest {

  @Test
  public void returnIntegerOrString() {
     Assert.assertTrue(SmartReturn.IntegerType.comeback("1") instanceof Integer);
     Assert.assertTrue(SmartReturn.DoubleType.comeback("1") instanceof Double);
  }

}