Billy Newman
10/11/2023, 3:38 PMBilly Newman
10/11/2023, 3:46 PM@Entity(...)
data class FooEntity()
@Entity(...)
data class BarEntity()
I would like each entity to implement some interface without polluting the entity class itself
interface Writeable {
fun write()
}
I am currently creating a wrapper object that implements the interface for each entity
class FooWriteable(private val foo: Foo): Writeable
class BarWriteable(private val bar: Bar): Writeable
Combing through the discussion here: https://discuss.kotlinlang.org/t/implementing-an-interface-for-an-existing-type/20967/11
It mentions receivers as a possible solution. Currently having trouble fully understanding. Am I heading down the right path with receivers? Could someone possibly at least point me in the right direction? Thanks!Johann Pardanaud
10/11/2023, 4:10 PMJohann Pardanaud
10/11/2023, 4:11 PMJohann Pardanaud
10/11/2023, 4:13 PMYoussef Shoaib [MOD]
10/11/2023, 5:00 PMinterface Writeable<T> {
fun T.write()
}
And have implementations of it defined:
object FooWriteable: Writeable<Foo> {
fun Foo.write() = TODO()
}
and then any function that takes a Writeable should instead be defined like so:
context(Writeable<W>)
fun <W> myCustomWrite(writeable: W) {
writeable.write()
}
And as you can see, you can't tell the difference on the callsite.Billy Newman
10/11/2023, 6:28 PMval foos = fooRepository.getFoos()
val bars = barRepository.getBars()
val writeables = foos + bars
myCustomWrite(writables)
Youssef Shoaib [MOD]
10/11/2023, 6:28 PMwith(FooWriteable)
Edit: oh in this case you might run into issues because Foo and bar have different types. Maybe myCustomWrite
could just take 2 different listBilly Newman
10/11/2023, 6:30 PMYoussef Shoaib [MOD]
10/11/2023, 6:34 PMUnionWriteable
that implements writeable for all those types