I have a class that stores a resultClass and I want to do some type checking and make sure users get a type safe list when calling the getTypeSafeResults function.
class MyClass<T>(
private val resultClass: Class<T>
){
fun getTypeSafeResults() : List<T> {
val results: List<Any?> = remoteFetchResults()
return results.filterIsInstance(resultClass)
}
}
This API must be Java friendly, hence why resultClass is a Java class.
But, when resultClass=Integer::class.java / resultClass=Long::class.java, and the results contain the Kotlin version of these e.g. kotlin.Int / kotlin.Long, they do not match the filterIsInstance(resultClass).
Is there is a way to manually check if the resultClass is the Java version of the Kotlin type? I've tried along the lines of this snippet below but had no luck:
(When it is a kotlin Long, it.javaClass.kotlin="class kotlin.Long" but resultClass="long")
fun getTypeSafeResults(results: List<Any?>) : List<T> {
return results.map {
uncheckedCast(
if (resultClass.isAssignableFrom(it.javaClass)) { // doesn't match kotlin long to java Long
it
} else if (it.javaClass.kotlin == resultClass) { // doesn't match kotlin long to java Long
it
} else {
throw Exception("Attempted to cast result of type ${it.javaClass} to $resultClass")
}
)
}
}