java conditional operator and different types

前端 未结 3 2100
死守一世寂寞
死守一世寂寞 2020-12-20 23:34

I have two methods in the Item Class:

public void setValue(String v);
public void setValue(Double v);

and I want to use Cond

3条回答
  •  粉色の甜心
    2020-12-20 23:56

    The Java Language Specification says

    [...]

    Otherwise, the second and third operands are of types S1 and S2 respectively. Let T1 be the type that results from applying boxing conversion to S1, and let T2 be the type that results from applying boxing conversion to S2. The type of the conditional expression is the result of applying capture conversion (§5.1.10) to lub(T1, T2).

    In your case, let's take T1 to be String and T2 to be Double.

    From the JLS, about the least upper bound (lub)

    The least upper bound, or "lub", of a set of reference types is a shared supertype that is more specific than any other shared supertype (that is, no other shared supertype is a subtype of the least upper bound).

    You can continue reading the JLS to workout the exact way the lub is calculated, but from the definition above we can see that what's provided in the compiler error message makes sense.

    Remember, the ternary operator is used as a single expression with a single value. That value must have a type at compile time. The JLS must therefore specify rules for it.

    Here's a related question/answer

    • Why doesn't the ternary operator like generic types with bounded wildcards?

提交回复
热议问题