Ilias Goormans
09/08/2023, 11:23 PMcontext (GroupBuilder<Arguments, Group>)
internal suspend inline fun addGroup() {}
internal suspend inline fun GroupBuilder<Arguments, Group>.addGroup() {}
xoangon
09/09/2023, 7:04 AMaddGroup
makes sense as an extension function of a GroupBuilder
.
There are other cases where you want some context injected into your function, but using an extension function doesn't feel semantically addequate. Say, for example, that you have some ErrorHandler
class and some API call. For this case:
// Doesn't feel right
suspend fun ErrorHandler.apiCall() { }
// This feels better
context(ErrorHandler)
suspend fun apiCall() { }
In the first case, you're implying that there's something in the meaning of the apiCall
function that would make it reasonable to have apiCall
as an static member function of ErrorHandler
. This is not really the case and, while in Java you would end up doing so. "This is not the way" mandalorian
In the second case, you'd read the function as "We need to be in the context of an ErrorHandler
to execute `apiCall`". This feels more explicit for this case