Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

234
Visualizações
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?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda