88. LVTI and the ternary operator

As long as it is written correctly, the ternary operator allows us to use different types of operands on the right-hand side. For example, the following code will not compile:

// Does not compile
List evensOrOdds = containsEven ?
List.of(10, 2, 12) : Set.of(13, 1, 11);

// Does not compile
Set evensOrOdds = containsEven ?
List.of(10, 2, 12) : Set.of(13, 1, 11);

Nevertheless, this code can be fixed by rewriting it using the correct/supported explicit types:

Collection evensOrOdds = containsEven ?
List.of(10, 2, 12) : Set.of(13, 1, 11);

Object evensOrOdds = containsEven ?
List.of(10, 2, 12) : Set.of(13, 1, 11);

A similar attempt will fail for the following snippet of code:

// Does not compile
int numberOrText = intOrString ? 2234 : "2234";

// Does not compile
String numberOrText = intOrString ? 2234 : "2234";

However, it can be fixed like this:

Serializable numberOrText = intOrString ? 2234 : "2234";

Object numberOrText = intOrString ? 2234 : "2234";

So, in order to have a ternary operator with different types of operands on the right-hand side, the developer must match the correct type that supports both conditional branches. Alternatively, the developer can rely on LVTI, as follows (of course, this works for the same types of operands as well):

// inferred type, Collection<Integer>
var evensOrOddsCollection = containsEven ?
List.of(10, 2, 12) : Set.of(13, 1, 11);

// inferred type, Serializable
var numberOrText = intOrString ? 2234 : "2234";

Don't conclude from these examples that the var type is inferred at runtime! It is NOT!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset