0

I've never used the ? operator before and I'm trying to figure out how it works.

I have been reading countless pages and decided to try for myself.

I have the following statement:

 getSelection().equalsIgnoreCase("Måned") ? calendarView.currentlyViewing.set(Calendar.Year) : showPopup();

As far as I can understand, if the left hand side (boolean) is true it will set my calendarView.to year and if not (getSelection is not equal to måned) it will call the method showPopup().

But when I type this into Eclipse I get a syntax error.

What am I doing wrong?

halfer
  • 19,824
  • 17
  • 99
  • 186
Marc Rasmussen
  • 19,771
  • 79
  • 203
  • 364
  • The suggested usage is this: `$name = isGirl()? 'Lauren' : 'Bob'` – andy Mar 27 '13 at 11:39
  • It's difficult to tell without an error message but my guess is that both these methods have a `void` return type. That's not how `?:` works, both statements on the RHS of `?` should evaluate to a non-void value. – biziclop Mar 27 '13 at 11:40

1 Answers1

15

You're trying to use the conditional ? : operator to decide which statement to execute. That's not its intention. The conditional operator can't be used as a statement - it's only to choose which expression to use as the overall result.

So this is fine:

foo(condition ? nonVoidMethod1() : nonVoidMethod2());

but this isn't:

condition ? voidMethod1() : voidMethod2();

You should just use an if statement here:

if (getSelection().equalsIgnoreCase("Måned")) {
    calendarView.currentlyViewing.set(Calendar.Year);
} else {
    showPopup();
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    Thank you i understand it now :P so the left hand side is a condition and then the right hand side decides what the variable needs to be – Marc Rasmussen Mar 27 '13 at 11:52