40

I want to use the ternary operator like this - checking only the true part of the statement:

foo() ? bar() : /* Do nothing */;

Is it possible to exclude the logic of the "else" part of this statement? I tried using return; but the compiler gives the error. Basically all I want to achieve is a statement using ternary operator which would look like this:

foo() ? bar();

Is this achievable?

domi
  • 968
  • 1
  • 10
  • 18
  • 1
    Why would you not just use `if`? (No, it's not possible) – Jeroen Vannevel Jun 15 '15 at 22:55
  • I am just curious if that's even possible. That is all. – domi Jun 15 '15 at 22:56
  • 3
    That doesn't actually make any sense. Expressions must have a value. – SLaks Jun 15 '15 at 22:57
  • 1
    I believe this is actually a desire to have a shorthand for simple if statements, keeping code compact (single line even with IDE formatters, no brackets). Closest semi-valid option is partial short-circuiting with foo() && bar(), since bar() only executes when foo() is true. – OXiGEN Aug 28 '20 at 04:01

2 Answers2

42

The ternary operator is usually used to immediately assign a value.

String a = bar() ? foo() : null;

For your usecase, you can simply use an if construct:

if (foo())
    bar();
wvdz
  • 16,251
  • 4
  • 53
  • 90
  • 1
    Not wrapping the if clause body in braces goes against the good code formatting practices, so this usually becomes if (foo()) { bar(); } (three lines) – Ivan Matavulj May 27 '16 at 09:25
  • 1
    @IvanMatavulj: that's a matter of taste, and most definitely not a generally accepted best practice. I personally feel brackets are redundant in this case and don't add to readability. I agree with this passionate answer on this topic: http://programmers.stackexchange.com/a/16550 – wvdz May 28 '16 at 12:53
  • 3
    I got an error using `null` I'd rather use `void(0)` – A. D'Alfonso Jun 10 '20 at 12:25
6

If it would work like that we wouldn't call it ternary anymore. I think the only way is that do something which does nothing. for example call a method which has empty body, or if you assign a value from this operation to a variable just assign a default value.

A.v
  • 734
  • 5
  • 26