What is the Java ?: operator called and what does it do?

前端 未结 16 1714
轮回少年
轮回少年 2020-11-21 05:27

I have been working with Java a couple of years, but up until recently I haven\'t run across this construct:

int count = isHere ? getHereCount(index) : getAw         


        
16条回答
  •  被撕碎了的回忆
    2020-11-21 06:26

    You might be interested in a proposal for some new operators that are similar to the conditional operator. The null-safe operators will enable code like this:

    String s = mayBeNull?.toString() ?: "null";
    

    It would be especially convenient where auto-unboxing takes place.

    Integer ival = ...;  // may be null
    int i = ival ?: -1;  // no NPE from unboxing
    

    It has been selected for further consideration under JDK 7's "Project Coin."

提交回复
热议问题