I have a problem making the initialization of a KCache cache generic. The code is as follows:
class MyCache(name: String, test: Boolean = true) {
private val cache: SortedMap<String, MyAvroObject>
init {
if (test) {
cache = sortedMapOf()
}
else {
val cacheProps = Properties()
cacheProps[KafkaCacheConfig.KAFKACACHE_BOOTSTRAP_SERVERS_CONFIG] =
appConfig.propertyOrNull("kafka.bootstrapServers")?.getString()
cacheProps[KafkaCacheConfig.KAFKACACHE_GROUP_ID_CONFIG] =
appConfig.propertyOrNull("applicationId")?.getString()
cacheProps[KafkaCacheConfig.KAFKACACHE_CLIENT_ID_CONFIG] = "GeneratingUnitsCache"
cacheProps[KafkaCacheConfig.KAFKACACHE_TOPIC_CONFIG] = "app.$name.kcache"
val serdeConfig = Collections.singletonMap(
AbstractKafkaSchemaSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG,
appConfig.property("kafka.schemaRegistryUrl").getString(),
)
//*** WISH TO MAKE THIS PART GENERIC
val avroSerdes: Serde<MyAvroObject> = SpecificAvroSerde()
avroSerdes.configure(serdeConfig, false)
cache = KafkaCache(
KafkaCacheConfig(cacheProps),
Serdes.String(),
avroSerdes
)
cache.init()
//***
}
}
}
Depending on which topic you consume from, the cache will contain different objects. For example, the cache could contain MyAvroObject, String or MyAvroObject2. The problem then becomes to initialize the cache with the correct Serdes (serializer / deserializer) depending on what kind of objects the cache will contain.
I have tried to make the actual definition of the cache generic:
class MyCache<T>(name: String, test: Boolean = true){
private val cache: SortedMap<String, T>
...
but then I struggle to get the type of T when I have to choose the right Serdes. Are there any Kotlin wizards out there who know if it is possible to make the initialization generic?