开发者

Ternary operator in varargs returning object or array is invalid

This is puzzling me and I would like an explanation.

public foo(EventPoint... eventPoints) { 
  //...
}


boolean isThisHappening;

foo(isThisHappening ? new EventPoint() : new EventPoint[]{});

Even though foo(new EventPoint()); is valid and foo(new EventPoint[]{}); is also valid. Is this the ternary operator failing due to type evaluation?

Using JDK 1.7.0 Getting the error:

required: EventPoint[] found: Object reason: argument type Object does not conform to vararg element type 开发者_StackOverflow中文版EventPoint


Is this the ternary operator failing?

The type of a ternary expression is basically the most specific subtype of the two last operands (JLS Reference). The most specific subtype of EventPoint and EventPoint[] is Object. If your var-arg method is declared to accept EventPoint... it simply won't work.

You should change

foo(state == ItemEvent.SELECTED ? (EventPoint) e.getItem()
                                : new EventPoint[]{});

to

foo(state == ItemEvent.SELECTED ? new EventPoint[] { (EventPoint) e.getItem() }
                                : new EventPoint[] { });

and it should compile just fine.


Pretty much. You are combining varargs, which isn't supported. You might want to call it like this:

foo(isThisHappening? new Object[]{new Object()} : new Object[]{});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜