Hello everyone. I want to share in an internal lib...
# getting-started
f
Hello everyone. I want to share in an internal library a repository that I use in several projects. But I am with trouble with generics. More details in the thread.
Copy code
interface HardwareType<T>

interface PeripheralType<T> {
    val peripheral: Peripheral
    val type: HardwareType<T>
}

interface PeripheralRepository<T> {
    val peripherals: StateFlow<Map<String, PeripheralType<T>>>
}

object PeripheralRepositoryImpl : PeripheralRepository <T> {
    override val peripherals: StateFlow<Map<String, PeripheralType<T>>>
        get() = TODO("Not yet implemented")
}
The repository is a object and one object can not has generics type. The HardwareType depends on client is consuming the library.
There are other approach can I use???
j
Why not just make the implementation a generic
class
instead of an
object
?
f
Because in first moment the repository is a singleton in my several projects. Implementing a generic
class
I will have to use a framework of injection or creating the repository in high level of the application and distributing to all the classes that use it. I think the second approach is coherent.
j
Mmh you could always do this in the consumers:
Copy code
val mySpecificRepo by lazy { PeripheralRepositoryImpl<SpecificT>() }
f
so using
by lazy
in the consumers (different classes) I get the same reference of object? I did not know about that.
I was wrong.
by lazy
do not guarantee the same reference of object
j
What do you mean? Lazy is synchronized by default and will compute the value the first time, and then reuse the same for every subsequent calls
f
j
But you have created 3 different properties here, so yes. Why not create just one property? I am assuming you were using an
object
before, that you declared once and used in different places. Similarly, you could declare a top-level property initialized lazily once, and use it everywhere
f
ahhh ok, I did not think in this way. works too.
thank you