Home > Software engineering >  Kotlin: Cast to unknown generic class
Kotlin: Cast to unknown generic class

Time:11-16

I have a relativly simple issue what I don't get solved: I want to cast to a dynamic generic:

class funnyClass(private val errorHandlers: List<ErrorHandler<*>>) {

fun funnyFun() {
  val errorType = findAnnotation(request)?.type ?: APIError::class
  errorHandlers.forEeach{ errorHandler ->
     val result = (errorHandler as? Errorhandler<errorType>).doSomething(...)
     ...
  }
  ...
}
...

Does anybody have an idea how it works?

Unfortuently I was not able to find it out by google this case.

CodePudding user response:

This is not possible and it would be meaningless to do so if you could. Casting it to something is to enable specific functions and properties of that object, or to be able to pass it as an argument to functions that require its type, at compile time. If you cast it to something without knowing what you are casting it to at compile time, then you aren't enabling anything that you can do at compile time.

  • Related