janvladimirmostert
05/26/2023, 9:04 PMinterface UserRepo {
sealed interface ListUsersResult {
...
}
fun listUsers(): ListUsersResult
}
class UserRepoPostgreSQL(val connection: Connection): UserRepo {
fun listUsers(): ListUsersResult {
// code that queries postgresql
}
}
class UserRepoDelegate(val userRepo: UserRepo): UserRepo by userRepo
so the above example, whenever I need a type in a service, I would mark the parameter type as the UserRepo
interface.
when I want to pass an instance of the interface, I will just create a UserRepoPostgreSQL(connection = ...)
Why would I need to do doSomething(userRepo = UserRepoDelegate(UserRepoPostgreSQL(connetion = ...)))
For test cases, I would just pass a FakeUserRepo()
instead of doSomething(userRepo = UserRepoDelegate(FakeUserRepo()))
I can think of some very advance use-cases for it, but then I could also just be passing the non-delegate instance in 99.99% of the cases.
Where does one typically use these interface delegates for?
Maybe some real-world use-cases would enlighten me.hho
05/27/2023, 1:27 AMdata class DataMessage(
val sender: String,
val category: Category,
val sendTimestamp: Instant,
// … lots more fields …
val contents: Map<String, Value>
) : Map<String, Value> by contents
I can use this just like I would use the "naked" map, but have all the additional fields around when I need themAdam S
05/27/2023, 8:31 AMMap<String, JsonElement>
can represent a JSON object and also be in the sealed hierarchy of JSON elements
https://github.com/Kotlin/kotlinx.serialization/blob/f83385276ce63fd8f76ce333a6f43ec095e9a1da/formats/json/commonMain/src/kotlinx/serialization/json/JsonElement.kt#L191-L194janvladimirmostert
05/27/2023, 8:55 AMclass Document(
private val printer: Printable,
private val storer: Storable
) : Printable by printer, Storable by storer
Document(printer = pdfPrinter, storer = s3)
or inside a test,
Document(printer = fakePrinter, storer = fakeStorage)
Thanks for the input!
I'll keep on digging and see if there's other cases where this pattern is usefulArjan van Wieringen
05/27/2023, 9:21 AMjanvladimirmostert
05/27/2023, 11:25 AMJohann Pardanaud
05/27/2023, 4:35 PMJohann Pardanaud
05/27/2023, 4:44 PM