Kotlin - Cannot use parameter T as parameter of type reified. Use a class instead

I have a simple helper function to get the value from SharedPreferences, like this:

operator inline fun <reified T : Any> SharedPreferences.get(key: String, defaultValue: T? = null): T? {
    return when (T::class) {
        String::class -> getString(key, defaultValue as? String) as T?
        Int::class -> getInt(key, defaultValue as? Int ?: -1) as T?
        Boolean::class -> getBoolean(key, defaultValue as? Boolean ?: false) as T?
        Float::class -> getFloat(key, defaultValue as? Float ?: -1f) as T?
        Long::class -> getLong(key, defaultValue as? Long ?: -1) as T?
        else -> throw UnsupportedOperationException("Not yet implemented")
    }
}

I used the reified type parameter to switch the class type, and since it is an operator function, I should be able to call the syntax with square brackets, as shown below:

val name: String? = prefs[Constants.PREF_NAME]

But every time I call it, a UnsupportedOperationException is thrown, indicating that the function cannot get the class type.

When I attach a debugger and evaluate T::class, it gives me an error"Cannot use 'T' as reified type parameter. Use a class instead."

What happened to my function? I could not catch the mistake. can anyone help?

: .

:. , Kotlin. https://youtrack.jetbrains.com/issue/KT-17748 https://youtrack.jetbrains.com/issue/KT-17748 .

+4
1

, , Int::class Int?::class ( ).

:

println(T::class)

get val age: Int? = prefs["AGE", 23], , java.lang.Integer.

, Int? java.lang.Integer.

( ) Java , :

operator inline fun <reified T : Any> get(key: String, defaultValue: T? = null): T? {
    return when (T::class) {
        String::class -> getString(key, defaultValue as? String) as T?
        java.lang.Integer::class -> getInt(key, defaultValue as? Int ?: -1) as T?
        java.lang.Boolean::class -> getBoolean(key, defaultValue as? Boolean ?: false) as T?
        java.lang.Float::class -> getFloat(key, defaultValue as? Float ?: -1f) as T?
        java.lang.Long::class -> getLong(key, defaultValue as? Long ?: -1) as T?
        else -> throw UnsupportedOperationException("Not yet implemented")
    }
}
+2

Source: https://habr.com/ru/post/1679506/


All Articles