Hello, why when i try do something like this it's ...
# announcements
a
Hello, why when i try do something like this it's doesn't compile reason: Incompatible types: String and Class<T>
Copy code
class TypeClass<T>(
    private val returnResultAs: Class<T>
) {

    fun testCast(value: String): Result<Any, Exception> = when (returnResultAs) {
        is String -> Result.of { value }
        else -> Result.of { Gson().fromJson(value, returnResultAs) }
    }

}
But if i added
Copy code
returnResultAs as Any
it works.
Copy code
class TypeClass<T>(
    private val returnResultAs: Class<T>
) {

    fun testCast(value: String): Result<Any, Exception> = when (returnResultAs as Any) {
        is String -> Result.of { value }
        else -> Result.of { Gson().fromJson(value, returnResultAs) }
    }

}
t
Your 'returnResultAs' var is a class reference, so in when clause you check if this reference is String. You should write 'String::class.java' instead of cast.
a
Thanks!