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

846
Visualizações
Error Kotlin: Type mismatch: inferred type is T? but Nothing was expected
class MyExample {
  abstract class Field<in E, T : Any>(private val getter: (E) -> T?) {
    fun get(entity: E): T? { return getter(entity) }
  }

  interface Meta<T: Any> {
    fun getFields(): List<MyExample.Field<T, *>>
  }


  interface MetaRepository {
    fun <T : Any> getMeta(klass: KClass<T>): Meta<T>?
  }

  lateinit var metaRepository: MetaRepository

  fun <T : Any> doSomthing(entity: T?) {

    val meta = metaRepository.getMeta(entity!!::class)!!

    meta.getFields().forEach { field ->
      val fieldValue = field.get(entity) // <-- Error Kotlin: Type mismatch: inferred type is T? but Nothing was expected
      Unit
    }
  }
}

Does anyone know why the compilation error "Error Kotlin: Type mismatch: inferred type is T? but Nothing was expected" is produced for the code above? How can I solve this error?

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

0

Look at

val meta = metaRepository.getMeta(entity!!::class)!!

What type do you expect for meta? Probably Meta<T>. But if you try to annotate it, you'll see that's wrong. It's actually inferred to be Meta<out T> (basically because entity could actually belong to some subclass of T, so entity!!::class is KClass<out T>).

So field is Field<Nothing, out Any> and field.get needs Nothing as its argument.

The solution is reified type parameters to get KClass<T> instead:

inline fun <reified T : Any> doSomthing(entity: T?) {

    val meta = metaRepository.getMeta(T::class)!!

    meta.getFields().forEach { field ->
        val fieldValue = field.get(entity!!)
        // Unit at the end isn't needed
    }
}

Unfortunately, getMeta itself can't use reified because it's an interface method and there's nothing to inline, but you can make a helper method to simplify calls to it:

inline fun <reified T : Any> MetaRepository.getMeta1() = getMeta(T::class)

...
val meta = metaRepository.getMeta1<T>()!!

Side note: if you need entity not to be null anyway (using entity!!), there's probably no good reason to make its type T? instead of T.

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