0

Is there any way to run void method in short if statement? For example I want to modify myList(it is class field) if myValue is set to true.

It works(if myMethod returns list) for:

mylist = myValue ? myMethod() : myList;

Is it possible to run it like (if myMethod is void):

myValue ? myMethod() : ;

and then modify myList only in myMethod?

slim
  • 40,215
  • 13
  • 94
  • 127
Paul Gerbert
  • 35
  • 1
  • 6
  • 3
    why not just do the obvious and `if(yourcondition) { runWhateverCodeYouLike();}`? – OH GOD SPIDERS Feb 06 '17 at 10:43
  • 4
    The ternary operator (`cond ? value1 : value2`) is **not** a "short if statement". It is an **operator**, which is used in the context an expression of a certain type is expected. What does `myMethod()` return? Does it make sense for its result to be used in that expression? And note the syntax includes a question mark. – RealSkeptic Feb 06 '17 at 10:50
  • 2
    This practice will lead to a code obfuscation, a plain old `if` will be much more readable and as short as a ternary – Anthony Raymond Feb 06 '17 at 10:50
  • why don't you [kiss](https://en.wikipedia.org/wiki/KISS_principle)? – Gabriel Feb 06 '17 at 12:05

2 Answers2

3

No. Java language does not allow this. From Java language specification:

It is a compile-time error for either the second or the third operand expression to be an invocation of a void method.

1

No you can't. The ternary operator b ? x : y (where b, x and y are statements) evaluates to something.

  • b must evaluate to a boolean
  • x must evaluate to a value (either a primitive or an object)
  • y must evaluate to a value of the same type as x
  • the statement as a whole evaluates to a value of the same type as x and y

I suppose you could imagine a language in which when x and y do not evaluate to a value, then the statement b ? x : y does not evaluate to a value either. In that language, r = b ? x : y would be an illegal statement when r = x or r = y were illegal statements.

But Java is not that language. In Java the ternary operator always has to return something (even if you don't use the result), and therefore so must its second two operands.

It's not normal to call the ternary operator "the short if statement".

In your use case, use if and else.

slim
  • 40,215
  • 13
  • 94
  • 127