Is there any benefit of using a context receiver h...
# getting-started
i
Is there any benefit of using a context receiver here instead of an extension function? Except from the fact that you can add multiple receivers in the context.
Copy code
context (GroupBuilder<Arguments, Group>)
internal suspend inline fun addGroup() {}

internal suspend inline fun GroupBuilder<Arguments, Group>.addGroup() {}
x
The main difference for these cases is semantic. For your case, I'd say that it makes perfect sense to use an extension function, as
addGroup
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:
Copy code
// 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
👍 1
1