开发者

? Operator Does Not Work

开发者 https://www.devze.com 2023-01-21 05:59 出处:网络
How come this is not possible? I am getting 开发者_开发技巧illegal start of expression. (s1.charAt(i) == \' \') ? i++ : break;

How come this is not possible? I am getting 开发者_开发技巧illegal start of expression.

(s1.charAt(i) == ' ') ? i++ : break;


The thing to understand here is that the ?: operator is used to return a value. You're basically calling a function that looks like this in that line:

anonymous function:
    if(s1.charAt(i) == ' '):
        return i++;
    else:
        return break;

Makes no sense, right? The ?: operator was only designed as a shorthand for if/else return statements like the above, not a replacement of if/else altogether.


You cannot use break in part of a ternary conditional expression as break isn't an expression itself, but just a control flow statement.

Why not just use an if-else construct instead?

if (s1.charAt(i) == ' ') {
    i++;
} else {
    break;
}


The ternary operator is an expression, not a statement. Use if ... else ... for this.


Of course it works. But it's an operator. Since when was a statement such as 'break' an operand?


I recommend avoiding the ternary (?:) operator EXCEPT for simple assignments. In my career I have seen too many crazy nested ternary operators; they become a maintenance headache (more cognitive overload - "don't make me think!").

I don't ban them on my teams, but recommend they are used judiciously. Used carefully they are cleaner than a corresponding if/else construct: -

public int ifFoo() {
    int i;

    if( isSomethingTrue()) {
        i = 5;
    }
    else {
        i = 10;
    }

    return i;
}

Compared to the ternary alternative: -

public int ternaryFoo() {
    final int i = isSomethingTrue()
                ? 5
                : 10;

    return i;
}

The ternary version is: -

  • Shorter
  • Easier to understand (my opinion, of course!)
  • Allows the variable to be "final"; which simplifies code comprehension; in a more complex method, someone reading the code knows no further code will try and modify the variable - one thing less to worry about.
0

精彩评论

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