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
Tesserakt
12/12/2019, 12:41 PM
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.