-2

As we all now, you can use ternary operators like this:

String testString = "test";
int myInt = testString.equals("test") ? 1 : 2;

However, how can I do so with methods? Assume I have the following:

String testString = "test";
if (testString.equals("test") {
    doSomething();
} else {
    doSomethingElse();
}

Is there something where you can combine this like the following manner:

testString.equals("test") ? doSomething() : doSomethingElse();

When using it in Android studio, it results in saying "not a statement"

Edit It can be done by initializing a local variable, but it is a bit unusual.

public void test() {
    String testString = "test";
    boolean test = testString.equals("test") ? doSomething() : doSomethingElse(); 
}

public boolean doSomething() {
    return true;
}

public boolean doSomethingElse() {
    return false;
}
Jason
  • 1,658
  • 3
  • 20
  • 51
  • 1
    You can. And you have the good syntax. – Turtle Jun 06 '17 at 13:39
  • No you can't! it refers to it as "not a statement" – Jason Jun 06 '17 at 13:39
  • 2
    Use the `if` statement. It is already exactly what you want. The ternary operator is not a drop-in replacement for any `if` statement. – khelwood Jun 06 '17 at 13:41
  • And btw: the good OO method of doing this is: `ThisOrThat whoCares = myFactory.getDoerFor("test"); whoCares.doIt()`. You **hide** the if as much as possible, and you then turn to OO/polymorphism with different implementation of the same interface. – GhostCat Jun 06 '17 at 13:44

1 Answers1

1

You can only write

testString.equals("test") ? doSomething() : doSomethingElse();

if doSomething() and doSomethingElse() both return something, and those somethings have either exactly the same type, or are covariant types. Setting both functions to return a boolean would be sufficient.

This is because the entire thing is an expression, and an expression has a value as well as a well-defined type.

If you are not wanting to do anything with the return value, then use an if statement.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • The only thing I can think of that will maybe resolve this is by letting both methods return a boolean, and let it be initialized as a variable. Example: ```boolean test = testString.equals("test") ? doSomething() : doSomethingElse();``` Where ```public boolean doSomething() {return true;}``` and ```public boolean doSomethingElse() {return false;}``` – Jason Jun 06 '17 at 16:17