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

2022-09-02 00:32:15

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 return Boolean FALSE

Is there a way to write a function that can return an or a ?intBoolean


Ok, so this has received a lot of responses. I understand I'm simply approaching the problem incorrectly and I should some sort of Exception in the method. To get a better answer, I'm going to provide some example code. Please don't make fun :)throw

public class Quad {

  public static void main (String[] args) {

    double a, b, c;

    a=1; b=-7; c=12;
    System.out.println("x = " + quadratic(a, b, c, 1));   // x = 4.0
    System.out.println("x = " + quadratic(a, b, c, -1));  // x = 3.0


    // "invalid" coefficients. Let's throw an exception here. How do we handle the exception?
    a=4; b=4; c=16;
    System.out.println("x = " + quadratic(a, b, c, 1));   // x = NaN
    System.out.println("x = " + quadratic(a, b, c, -1));  // x = NaN

  }

  public static double quadratic(double a, double b, double c, int polarity) {

    double x = b*b - 4*a*c;

    // When x < 0, Math.sqrt(x) retruns NaN
    if (x < 0) {
      /*
        throw exception!
        I understand this code can be adjusted to accommodate 
        imaginary numbers, but for the sake of this example,
        let's just have this function throw an exception and
        say the coefficients are invalid
      */
    }

    return (-b + Math.sqrt(x) * polarity) / (2*a);

  }

}

答案 1

No, you can't do that in Java.

You could return an though. And by returning an object you could technically return a derived class such as or . However, I don't think it's the best idea.Objectjava.lang.Integerjava.lang.Boolean


答案 2

You could technically do this:

public <T> 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.