Can someone please tell why the type R below is be...
# announcements
g
Can someone please tell why the type R below is being erased even though it is reified?
Copy code
class BaseResponse<T> {
    val data: T? = null
    var someMessage: String? = null
}

class User {
    val name: String? = null
}

fun main() {
    val name = getUser<User>().data?.name
    println(name)
}

inline fun <reified R> getUser(): BaseResponse<R> {

    return if (testMessage == null) {
        BaseResponse<R>().apply { someMessage = "Some error" }
    } else {
        Gson().fromJson(
            testMessage,
            object : TypeToken<BaseResponse<R>>() {}.type
        )
    }
}

val testMessage: String? = """{"data": {"name":"Adam"},"someMessage":""}"""
Error -
Copy code
Exception in thread "main" java.lang.ClassCastException: class com.google.gson.internal.LinkedTreeMap cannot be cast to class User (com.google.gson.internal.LinkedTreeMap and User are in unnamed module of loader 'app')
	at MainKt.main(main.kt:54)
	at MainKt.main(main.kt)
If I send BaseResponse<User> as R instead of just User and return R, it works fine. But I want to return BaseReponse<R>.
Happy to provide more info. Thanks
s
I havent fully read your code but I think its the same issue as this: https://youtrack.jetbrains.com/issue/KT-22798
✔️ 1
👍 1