How to write Java function that returns values of multiple data types?

后端 未结 11 1563
耶瑟儿~
耶瑟儿~ 2021-01-03 23:34

For example, I want to create a function that can return any number (negative, zero, or positive).

However, based on certain exceptions, I\'d like the function to re

11条回答
  •  再見小時候
    2021-01-03 23:49

    You could technically do this:

    public  T doWork()
    {
       if(codition)
       {
          return (T) new Integer(1);
       }
       else
       {
          return (T) Boolean.FALSE;
       }
    }
    

    Then this code would compile:

    int x = doWork(); // the condition evaluates to true
    boolean test = doWork();
    

    But you could most certainly encounter runtime exceptions if the method returns the wrong type. You also must return objects instead of primitives because T is erased to java.lang.Object, which means the returned type must extend Object (i.e. be an object). The above example makes use of autoboxing to achieve a primitive return type.

    I certainly wouldn't recommend this approach because IMO you need to evaluate your use of exception handling. You catch exceptions in exceptional cases if you can do something with that exception (i.e. recover, persist, retry, etc.). Exceptions are an exception to the expected workflow, not a part of it.

提交回复
热议问题