'Switch pattern matching for instanceof returns always null
I am trying to assign the result of the following instanceof pattern matching switch to the variable languageCodeOfReturnValue.
String languageCodeOfReturnValue = switch (object){
case PlantGuidePageWrapperDTO plantGuidePageWrapperDTO -> plantGuidePageWrapperDTO.getSeedDetailsDTO().getPageSummaryLanguageCode();
case JournalEntryDetailsDTO journalEntryDetailsDTO -> journalEntryDetailsDTO.getLanguageCode();
case JournalOverviewDTO journalOverviewDTO -> journalOverviewDTO.getPageSummaryLanguageCode();
default -> null;
};
But this code causes the following warning:
Value 'switch (object){ case PlantGuidePageWrapperDTO plantGuidePageWrapperDTO -> plant...' is always 'null'
When i remove the default clause the warning disappears but then i'm left with a syntax error because then the switch doesn't cover all possible values. The warning disappears when i replace null with and empty string ''. However i really want the default value to be null.
So my question is twofold: First, why is the switch statement result always null when i return a null value in the default case. And second, What then is the proper way to return a null value when none of the patterns match?
Thank you
EDIT: I am using Intellij IDEA as IDE. Perhaps its an inellij IDEA bug?
Solution 1:[1]
Your switch statement looks correct. Based solely on the IntelliJ warning, it seems like all your individual cases statements return a null value. As you mention when you change the default to an empty string the warning disappears as now all the case statements do not return null values.
Additionally, when dealing with nulls you could always use Optional values.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jeremy Dsilva |
