Helio
05/06/2021, 8:02 AMCannot 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.
@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)
}
}
Roukanken
05/06/2021, 8:08 AMJson.encodeToString
is a "reified inline function", eg, it's signature looks smth like this:
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 complainingRoukanken
05/06/2021, 8:20 AMKClass<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)Helio
05/06/2021, 8:41 AM