如何编写返回多种数据类型值的Java函数?

新手上路,请多包涵

例如,我想创建一个可以返回任何数字(负数、零或正数)的函数。

但是,基于某些例外情况,我希望函数返回 Boolean FALSE

有没有办法编写一个可以返回 int Boolean 的函数?


好的,所以这收到了很多回复。我知道我只是错误地解决了问题,我应该 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);

  }

}

原文由 maček 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 893
2 个回答

不,你不能在 Java 中这样做。

不过,您可以返回 Object 。通过返回一个对象,您可以在技术上返回一个派生类,例如 java.lang.Integerjava.lang.Boolean 。但是,我认为这不是最好的主意。

原文由 Pablo Santa Cruz 发布,翻译遵循 CC BY-SA 2.5 许可协议

你可以在技术上做到这一点:

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

然后这段代码将编译:

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

但是如果方法返回错误的类型,您肯定会遇到运行时异常。您还必须返回对象而不是原语,因为 T 被擦除为 java.lang.Object,这意味着返回的类型必须扩展 Object(即是一个对象)。上面的示例使用自动装箱来实现原始返回类型。

我当然不会推荐这种方法,因为在 IMO 中,您需要评估您对异常处理的使用。如果您可以对异常执行某些操作(即恢复、坚持、重试等),那么您可以在异常情况下捕获异常。异常是预期工作流的 _异常_,而不是它的一部分。

原文由 hisdrewness 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题