简体   繁体   English

方法可以返回不止一种类型

[英]Can method return more than one type

I am new to Java and trying to understand the below code:我是 Java 新手并试图理解以下代码:

int someMethod() {
    return (true ? null : 0);
}

The method's return type is int , but it can return both null and int , is this correct behavior in Java?该方法的返回类型是int ,但它可以返回nullint ,这是 Java 中的正确行为吗? Can a Java method return more than one type? Java 方法可以返回多个类型吗? This may sound silly for those who are experienced, but I have just took my first step in Java.对于有经验的人来说,这可能听起来很愚蠢,但我刚刚在 Java 中迈出了第一步。

A method cannot return more than one type.一个方法不能返回多个类型。

The signature of a method contains the return type or void if the method doesn't return anything.如果方法不返回任何内容,则方法的签名包含返回类型或void Since it must be defined in the method signature, you must return something of that type.由于它必须在方法签名中定义,因此您必须返回该类型的内容。

The code编码

return (true ? null : 0);

is a shorthand if-else statement, or conditional ternary expression, and can be rewritten to this:是 if-else 语句或条件三元表达式的速记,可以改写为:

if (true) {
    return null;
}
else {
    return 0;
}

The above code, however, won't compile since one cannot return null if the return type is the primitive type int . 但是,上面的代码将无法编译,因为如果返回类型是 原始类型 int则无法返回 null The above code will compile, because the JVM will try to convert null to an int , due to auto-unboxing.上面的代码会编译,因为 JVM 会尝试将 null 转换为int ,这是由于自动拆箱。 At runtime, it will throw a NullPointerException , as pointed out by Eran .在运行时,它会抛出NullPointerException ,正如Eran指出的

In order to 'return multiple types', you could do the following:为了“返回多种类型”,您可以执行以下操作:

public class BooleanOrInt {

    private boolean isInteger; // Whether value is boolean or int
    private boolean b;
    private int i;

    public BooleanOrInt(boolean b) {
        this.b = b;
        this.isInteger = false;
    }

    public BooleanOrInt(int i) {
        this.i = i;
        this.isInteger = true;
    }

    public boolean isInteger() {
        return this.isInteger;
    }
}

And then your code should be as follows:然后你的代码应该如下:

BooleanOrInt methodOfA() {
    if (someCondition) {
        return new BooleanOrInt(theBooleanYouWant);
    }
    else {
        return new BooleanOrInt(theIntegerYouWant);
    }
}

It's a conditional ternary expression, which means the method returns one of the two values following the ?这是一个条件三元表达式,这意味着该方法返回?后面的两个值之一? , depending on the evaluation of the condition he appears prior to ? ,取决于对他出现之前的条件的评估? (which in your case always returns true ). (在你的情况下总是返回true )。

The type of the expression (true ? null : 0) is Integer , since that's the common type for null and 0 .表达式的类型(true ? null : 0)Integer ,因为这是null0的常见类型。

Your code will throw a NullPointerException , since when you return a null Integer in a method whose return type is int , the JVM attempts to convert the Integer to int and fails.您的代码将抛出NullPointerException ,因为当您在返回类型为int的方法中返回null Integer时,JVM 尝试将Integer转换为int并失败。

In order to fix this code, you'll have to change the return type to Integer (which is the reference type that serves as a wrapper for the int primitive type) :为了修复此代码,您必须将返回类型更改为Integer (这是用作int原始类型包装器的引用类型):

Integer methodOfA()
{
    return (true ? null : 0);
}

Java method cannot return more than one type in the form you are suggesting. Java 方法不能以您建议的形式返回一种以上的类型。 However, it can return any number of sub-types.但是,它可以返回任意数量的子类型。 In your case, int is a primitive type and it cannot have sub-types.在你的情况下, int 是一种原始类型,它不能有子类型。 Here you cannot return null since null can only be returned by methods whose return type is an object.在这里您不能返回 null,因为 null 只能由返回类型为对象的方法返回。 For primitives you have to specify some values (0 in your case).对于基元,您必须指定一些值(在您的情况下为 0)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM