Re: Incompatable conditional operand types
- From: Chris Smith <cdsmith@xxxxxxx>
- Date: Fri, 6 Jan 2006 16:36:04 -0700
<carl.manaster@xxxxxxxxx> wrote:
> Half half = heightBefore() > heightAfter() ? after : before;
>
> And it doesn't like this line. It tells me, "incompatible conditional
> operand types After and Before".
That code is illegal in Java 1.4, but legal in Java 1.5. For 1.4, the
relevant section of the Java Language Specification is 15.25, which
says:
"If the second and third operands are of different reference types,
then it must be possible to convert one of the types to the other
type (call this latter type T) by assignment conversion (§5.2); the
type of the conditional expression is T. It is a compile-time error
if neither type is assignment compatible with the other type."
Since after can't be assigned to type of before, and before can't be
assigned to the type of after, the expression is illegal. You can solve
the problem by casting to the desired type explicitly in one or both of
the latter two operands.
Half half = heightBefore() > heightAfter() ? (Half) after : before;
The rules defined in Java 1.4 are conservative... that is, there are
safe operations such as yours that they exclude. But they are the rules
nevertheless.
Java 1.5 modifies that statement in section 15.25 to require a capture
conversion of the "lub" type operator, which is defined for type
parameter inference of methods as part of generics. The new version is
less conservative, and accepts your code as legal. In Java 1.5, the
resulting type of that expression is some beastly thing that's not
representable in Java at all, but is nevertheless assignment compatible
with Half. Indeed, it even accepts this rather surprising code:
public class Test
{
private static class A { }
private static interface X { }
private static class B extends A implements X { }
private static class C extends A implements X { }
public static void main(String[] args)
{
boolean b = true;
A a = b ? new B() : new C();
X x = b ? new B() : new C();
}
}
--
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
.
- Follow-Ups:
- Re: Incompatable conditional operand types
- From: carl . manaster
- Re: Incompatable conditional operand types
- References:
- Incompatable conditional operand types
- From: carl . manaster
- Incompatable conditional operand types
- Prev by Date: Re: Why do I get no IO exception ?
- Next by Date: Re: Minimizing Compile Time Dependencies
- Previous by thread: Incompatable conditional operand types
- Next by thread: Re: Incompatable conditional operand types
- Index(es):
Relevant Pages
|