Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

836
Views
Error Kotlin: Tipo no coincidente: ¿el tipo inferido es T? pero nada se esperaba
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 } } }

¿Alguien sabe por qué se produce el error de compilación "Error Kotlin: Type mismatch: inferred type is T? but Nothing was expected" para el código anterior? ¿Cómo puedo solucionar este error?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Mirar

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

¿Qué tipo esperas para meta ? Probablemente Meta<T> . Pero si intenta anotarlo, verá que está mal. En realidad, se infiere que es Meta<out T> (básicamente porque la entity en realidad podría pertenecer a alguna subclase de T , por lo que entity!!::class es KClass<out T> ).

Por lo tanto field es Field<Nothing, out Any> y field.get necesita Nothing como argumento.

La solución son los parámetros de tipo cosificados para obtener KClass<T> en su lugar:

 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 } }

Desafortunadamente, getMeta en sí mismo no puede usar reified porque es un método de interfaz y no hay nada que insertar, pero puede crear un método auxiliar para simplificar las llamadas:

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

Nota al margen: si necesita que la entity no sea null de todos modos (¡usando la entity!! ), ¿Probablemente no haya una buena razón para hacer su tipo T? en lugar de T

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!