If without else ternary operator

前端 未结 10 674
太阳男子
太阳男子 2020-12-05 17:04

So far from I have been searching through the net, the statement always have if and else condition such as a ? b : c. I would like to know whether the if<

相关标签:
10条回答
  • 2020-12-05 17:21

    Yes you can do that actually (in JavaScript at least):

    condition && x = true;
    

    or (in JavaScript, and there might be a similar way to do this in Java):

    void(condition && x = true)
    
    0 讨论(0)
  • 2020-12-05 17:23

    A ternary operation is called ternary beacause it takes 3 arguments, if it takes 2 it is a binary operation.

    And as noted above, it is an expression returning a value.

    If you omit the else you would have an undefined situation where the expression would not return a value.

    So as also noted in other answer, you should use an if statement.

    0 讨论(0)
  • 2020-12-05 17:25

    Well in JavaScript you can simply do:

    expression ? doAction() : undefined
    

    since that's what's literally actually happening in a real if statement, the else clause is simply undefined. I image you can do pretty much the same thing in (almost?) any programming language, for the else clause just put a null-type variable that doesn't return a value, it shouldn't cause any compile errors.

    0 讨论(0)
  • 2020-12-05 17:30

    Ternary if operator is the particular ternary operator. One of a kind.

    From Wiki:

    In mathematics, a ternary operation is an n-ary operation with n = 3.

    It means all 3 operands are required for you.

    0 讨论(0)
  • 2020-12-05 17:30

    You cannot use ternary without else, but to do a "if-without-else" in one line, you can use Java 8 Optional class.

    PreparedStatement pstmt;
    
    //.... 
    
    Optional.ofNullable(pstmt).ifPresent(pstmt::close); // <- but IOException will still happen here. Handle it.
    
    0 讨论(0)
  • 2020-12-05 17:35

    As mentioned in the other answers, you can't use a ternary operator to do this.

    However, if the need strikes you, you can use Java 8 Optional and lambdas to put this kind of logic into a single statement:

    Optional.of(pstmt).ifPresent((p) -> p.close())
    
    0 讨论(0)
提交回复
热议问题