Rafał Sokalski
Rafał Sokalski

Reputation: 2007

Weird behavior of ternary operator

I have weird situation which I cannot explain after debugging. I want to set label text with that pattern:

POI: "replacement"

Replacement depends on ternary operation which looks like this:

label.setText("POI: " + requestItem.getPoi() != null ? requestItem.getPoi() : "#####")

requestItem.getPoi() returns type of String and I want to check if it returns String or null. If null I want to set '#####'.

Problem is with requestItem.getPoi() != null ? requestItem.getPoi() : "#####"

When I evaluate this value in debugger when requestItem.getPoi() returns null debugger throws "Type mismatch: Cannot convert from String to void".

Anyone has an idea what is wrong with this operation ?

Upvotes: 0

Views: 462

Answers (1)

Óscar López
Óscar López

Reputation: 235984

The problem is caused by operator precedence, you must surround the ternary expression between parentheses. Try this:

"POI: " + (requestItem.getPoi() != null ? requestItem.getPoi() : "#####")

Upvotes: 5

Related Questions