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

159
Visualizações
Intellij not recognizing wrong return type

I have this method:

public <T extends CacheResult> T get(Object key, CacheDefinition cacheDefinition) {
    return load(key, cacheDefinition.name(), cacheDefinition.getTypeReference());
}

Now my IDE complains (as expected, and which is correct) about this line, because the return type is supposed to be CacheResult

User user = spxCacheManager.get(username, CacheDefinition.USERS_BY_USERNAME);

What I currently dont understand, is that the IDE (IntelliJ) is not complaining about this:

List<User> usersFromCache = spxCacheManager.get(username, CacheDefinition.USERS_BY_USERNAME);

Which is actually wrong. What am I missing here?

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

0

This works because T gets inferred as an intersection type - List<User> & CacheResult & Object. After all, why can't a class both implement List<User> and implement/extend CacheResult? Such a type is certainly possible!

You can see this happen by writing a toy program and using the --debug=verboseResolution=all option:

import java.util.List;

public class Main {

  public static void main(String[] args) {
    List<User> u = new Main().get();
  }

  public <T extends CacheResult> T get() {
    return null;
  }
}

interface CacheResult {}
class User implements CacheResult {}

javac with verboseResolution=all would output:

  instantiated signature: ()INT#1
  target-type: List<User>
  where T is a type-variable:
    T extends CacheResult declared in method <T>get()
  where INT#1 is an intersection type:
    INT#1 extends Object,List<User>,CacheResult

You can also follow through the process of how Java does type inference. Eventually (somewhere in "resolution"), you'll reach a point where you need to find the greatest lower bound ("glb") of Object, List<User> and CacheResult, and that type is exactly their intersection type, as defined here.

On the other hand, your code won't compile if CacheResult is a class, and the type you are assigning the method result to is an unrelated class, since no class can inherit from two unrelated classes.

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