Using the Java 1.4 compiler causes an "incompatible types for ?: neither is a subtype of the other" error, though. To fix it, we have to help out the compiler with a bit of DWIM:
I myI = true ? ((I) new A()) : ((I) new B());
I really have to make a push to get this code running on a newer JVM...
Lester Burnham wrote:Yep, that's the one I found, too (see my first post :-)
BTW, it didn't make a difference if I was a class that both A and B extended - same error.
Please ignore my post - once again I am guilty of not reading right to the bottom of a posting.
I'm surprised it does not work. Looks like you are going to have to use an explicit if-then-else construct. If that fails to compile then maybe a static method to hide the casting. If that fails then ...
The first and only time I encountered this bug I must have read the code about 10.000 times and when I finally found the bug I tested it on 2 different machines just to be sure. Later that month I read an article about it I believe it was an example of the Java Puzzlers book.
Wouter Oet wrote:It's highly discouraged to use the ternary operator in combination with different classes as result. For example this still fails on java version "1.6.0_17" (the latest version on my pc):
I think that has to do with auto-(un)boxing. It seems like, for some reason, the Integer and Double are unboxed again, then boxed to the highest type (Double). If I replace the Integer.valueOf(5) with new BigDecimal("5") then I get 5. That's because BigDecimal cannot be unboxed.