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

847
Views
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 answers
Answer question

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