Quantcast
Channel: JetBrains Developer Community : Thread List - IntelliJ IDEA Users
Viewing all articles
Browse latest Browse all 5661

Good code gray with conditional operator: bug?

$
0
0

Consider the following code:

 

           private @Nullable Integer foo(@Nullable String s, @Nullable Integer i) {               return s == null? i : (Integer) 2;           }

 

IDEA highlights the "(Integer)" cast in gray and suggests that "Casting '2' to 'Integer' is redundant". The question is, is it really?

 

Without the cast, the type of the expression  "s == null ? i : 2" is going to be int (it chooses between a reference and int primitive and picks the int primitive, see JLS 15.25); so "i" will be unboxed to an int if it is chosen. If you call foo(null, null), the unboxing with throw a NPE.

 

With the cast, the type of "s == null ? i : (Integer) 2" is an Integer (both operands 2 and 3 are of type Integer) and so if i happens to be null, that's fine and that's what gets returned. So foo(null, null) returns null.

 

In one case we can call foo(null, null) and in the other it throws, so the cast doesn't seem unnecessary. Should IDEA not suggest it gets removed?

 

(Note: whether one would write "(Integer) 2" is another debate )

 

   Vince.


Viewing all articles
Browse latest Browse all 5661

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>