https://kotlinlang.org logo
#getting-started
Title
# getting-started
h

Helio

05/06/2021, 8:02 AM
Hello 👋🏽 , Apologies if this is a silly question, but would anyone be able to help me understand what this error
Cannot use 'T' as reified type parameter. Use a class instead.
means in this situation? I’m trying to generalise the
decodeFromString
and
encodeFromString
but I’m confused why it doesn’t let me do that.
Copy code
@ExperimentalLettuceCoroutinesApi
abstract class RedisDAO<T>(
    private val keyPrefix: String,
    private val ttl: Long, private val redisClient: BbcRedisClient
) {

    open suspend fun getValueFromKey(key: String): T? {
        val extractedValue = redisClient.getValueFromKey(key)
        return extractedValue?.let { Json.decodeFromString<T>(it) }
    }

    open fun buildRedisKey(identifier: String): String {
        return "$keyPrefix$identifier"
    }

    open suspend fun saveWithTTL(key: String, value: T) {
        val encodedValue = Json.encodeToString<T>(value)
        redisClient.storeKeyWithTTL(key, encodedValue, ttl)
    }
}
r

Roukanken

05/06/2021, 8:08 AM
the probme is, that
Json.encodeToString
is a "reified inline function", eg, it's signature looks smth like this:
Copy code
inline fun <reified T> encodeToString(...)
what this reified keyword means, is, that compiler will figure out what class
T
is, and the function can use
T::class
inside itself, as compiler will pass it to it. Your problem is, that you are trying to pass this function
T
which is generics parameter of your class - that means you don't know what class
T
is, and neither compiler can figure it out. Which is why it's complaining
to solve it, you basically have to get
KClass<T>
from caller of this class, for example in constructor parameters. I haven't exactly looked up how you can call
encodeToString
with KClass, but I a quick search at least shows function
KClass<T>.serializer()
which returns serializer for that class. That should be passable to
encode
afaik... Anyways, ya gotta look up other non-reified overloads of
encode
(you can then create reified function as your "Fake" constructor, that will pass KClass or serializer to real constructor)
h

Helio

05/06/2021, 8:41 AM
Thank you very much! I will have a careful look at what you said. I will post the solution if I figure.
7 Views