If without else ternary operator

2019-01-17 19:31发布

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 ternary statement can be used without else. Assuming i have the following code, i wish to close the PreparedStatement if it is not null

(I am using Java programming language.)

PreparedStatement pstmt;

//.... 

(pstmt!=null) ? pstmt.close : <do nothing>;

8条回答
可以哭但决不认输i
2楼-- · 2019-01-17 19:33

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())
查看更多
家丑人穷心不美
3楼-- · 2019-01-17 19:33

It does seem a shame not to be able to use a ternary when building an array which has optional elements.

my $yn = 'N';
my $foo = [ { n => 'a' }, 
    ( $yn eq 'Y' ? { n => 'b' } : undef),
    { n => 'c' } ];
say Dumper $foo;

You really want nothing rather than undef or empty string.

This also gives you an empty element rather than 'nothing'.

my $yn = 'N';
my $foo = [ { n => 'a' },
$yn eq 'Y' && { n => 'b' },
{ n => 'c' } ];
say Dumper $foo;
查看更多
对你真心纯属浪费
4楼-- · 2019-01-17 19:35

Why using ternary operator when you have only one choice?

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

is enough!

查看更多
Bombasti
5楼-- · 2019-01-17 19:39

Just write it out?

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

It's the exact same length.

查看更多
Melony?
6楼-- · 2019-01-17 19:48

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.
查看更多
贼婆χ
7楼-- · 2019-01-17 19:49

No, you cannot do that. Instead try this:

if(bool1 && bool2) voidFunc1();
查看更多
登录 后发表回答