Julius J. Fischer
Julius J. Fischer

Reputation: 3

Kotlin: Cast to unknown generic class

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.

Upvotes: 0

Views: 375

Answers (1)

Tenfour04
Tenfour04

Reputation: 93531

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.

Upvotes: 1

Related Questions