如果没有其他三元运算符

到目前为止我一直在网上搜索,语句总是有 if 和 else 条件,如 a ? b : c。我想知道 if三元语句是否可以在没有 else的情况下使用。 假设我有以下代码,我希望关闭的 PreparedStatement,如果它不是空

(我使用的是 Java 编程语言。)

PreparedStatement pstmt;


//....


(pstmt!=null) ? pstmt.close : <do nothing>;
103115 次浏览

Just write it out?

if(pstmt != null) pstmt.close();

It's the exact same length.

No, you cannot do that. Instead try this:

if(bool1 && bool2) voidFunc1();

Why using ternary operator when you have only one choice?

if (pstmt != null) pstmt.close();

is enough!

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.

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.

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())

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.

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.

or just make a function to return if all else fails

function oy(x1,x2){if(x1) return x2();}


oy(etzem==6, ()=>yichoyliss=8);


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)

pstmt != null && pstmt.close;

The line of code above translates to When the left side of the expression "translates" to true -> execute the right side.

use:

<logic Expression> ? <method> : null;

Example:

(pstmt!=null) ? pstmt.close : null;

is dirty solution but works...