https://kotlinlang.org logo
Title
a

Alexjok

12/12/2019, 12:12 PM
Hello, why when i try do something like this it's doesn't compile reason: Incompatible types: String and Class<T>
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
returnResultAs as Any
it works.
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.
a

Alexjok

12/12/2019, 12:45 PM
Thanks!