Hi, Have question related to Generics. ```interfac...
# announcements
a
Hi, Have question related to Generics.
Copy code
interface DataProvider<T> {
    fun provideData(t:T): Data
}

class TaxDataProvider: DataProvider<Tax> {
    override fun provideData(t: Tax): Data {
        return Data()
    }
}

class Provider {
    fun register(dataProvider: DataProvider<*>) {
        dataProvider.provideData(Tax())  //Not able to call this. Getting error: Type mismatch Required Nothing. Found Tax
    }
}
Is there any way to achieve this? I wanted to keep register method to accept type of DataProvider not specific type (TaxDataProvider).
d
DataProvider accepts a T not a Tax; only in the case of the TaxDataProvider could you pass in a Tax. The register function can’t pass an instance of Tax to an arbitrary DataProvider
You could perhaps have
fun <T> register(DataProvider: DataProvider<T>, inputFunc: () -> T)
Then you’d be able to
DataProvider.provideData(inputFunc())
To get an instance of T that is compatible with your DataProvider
a
Thanks Dave! This works. One more question, I actually wanted to store this dataprovider in list (class member variable in Provider class) and access it later.
n
To store it, you'd need to then make Provider generic on the kind of provider you want to store
Either that, or give Data provider a base that doesn't depend on T
Or just store the data providers as a list of Any
a
It works with mutableListOf<Any> not with mutableListOf<DataProvider<Any>>. I think I can cast it later to correct type. Thanks this is helpful!
n
Yeah that's what I meant
Well, keep in mind you're sacrificing static type safety by doing this
You may want to take a step back and see what your overall goal is, design a bit differently, etc
m
It works if you declare the list like this
Copy code
val providers = mutableListOf<DataProvider<*>>()
then you can store your object
Copy code
fun <T> register(dataProvider: DataProvider<T>, inputFunc: () -> T) {
    providers.add(dataProvider) // OK
    dataProvider.provideData(inputFunc())
}