ursus
05/17/2025, 10:36 PMcontext parameters
? I'm struggling to see itPablichjenkov
05/17/2025, 11:15 PMPablichjenkov
05/17/2025, 11:16 PMYoussef Shoaib [MOD]
05/18/2025, 12:58 AMWout Werkman
05/18/2025, 7:44 AMsuspend fun User.isFriendsWith(other: User, repository: UserRepository): Boolean = ...
The last parameter feels different. The receiver and other
are a core part of what a reader needs to read to understand the behavior of the function. The repository is simply something that happens to be necessary (but not an implementation detail, those shouldn't be visible in signature at all), but it is not critical for the understanding the functions behavior.
Now you can write:
context(repository: UserRepository)
suspend fun User.isFriendsWith(other: User): Boolean = ...
I strongly believe that context parameters should not be used for parameters that are core to the behavior of the function. Which includes most parameters that are data.Youssef Shoaib [MOD]
05/18/2025, 8:12 AMcoeffects
as some literature calls them. The idea being that a function declares the capabilities it needs, and then inside it may use them freely. It basically declares what a function needs from its environment to be able to do its job.hfhbd
05/18/2025, 9:20 AMursus
05/18/2025, 10:39 AMUsers.isFriendsWith
? Since there to me it looks like just moving the param from one place to another and callsite is uglierCLOVIS
05/18/2025, 7:22 PMursus
05/18/2025, 7:23 PMCLOVIS
05/18/2025, 7:24 PMCLOVIS
05/18/2025, 7:26 PMrequest {
date = 12 jan 2025
}
But, you want jan
to only exist in your DSL (let's not pollute all other Int values!). Try that today, you'll see it's not that easy.CLOVIS
05/18/2025, 7:27 PMfun Int.jan(year: Int)
because that would be globally available.CLOVIS
05/18/2025, 7:29 PMinterface RequestDsl {
var date: LocalDateTime
// This *has* to be part of the interface, it can't be an extension, because you can only have a single receiver
infix fun Int.jan(year: Int): LocalDateTime = …
}
but that's not great, because you're not respecting extension-oriented design: jan
shouldn't really be in the interface, it's not the main functionality of the DSL. It's just a helper function.CLOVIS
05/18/2025, 7:30 PMinfix
.CLOVIS
05/18/2025, 7:31 PMinterface RequestDsl {
var date: LocalDateTime
}
context(dsl: RequestDsl)
infix fun Int.jan(year: Int): LocalDateTime = …
ursus
05/18/2025, 7:34 PMYoussef Shoaib [MOD]
05/18/2025, 7:36 PMCLOVIS
05/18/2025, 7:36 PMLoggerScope
, CoroutineScope
, ProgressReporter
, TracingSpan
, Arrow's Raise
stuff like that, but not repositories or services. I prefer those to be explicit.CLOVIS
05/18/2025, 7:37 PMEdgar Avuzi
05/19/2025, 7:42 AMPablichjenkov
05/19/2025, 12:55 PM