Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

843
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda