Default value for receiver types

I would like to have default values for receiver types. The syntax could look like this:

fun (CoroutineScope = GlobalScope).doSomething() {
  ...
}

You would be able to call it with or without a receiving type:

doSomething() // Calls with default receiver

CustomCoroutineScope.doSomething() // Calls with the given receiver

with (CustomCoroutineScope) {
  doSomething() // Calls with the given receiver
}

Currently we need to define two functions:

fun CoroutineScope.doSomething() { ... }

fun doSomething() = GlobalScope.doSomething()

To me the syntax looks simple enough that it shouldn’t confuse new users that already know about default parameters, and it would increase the language’s consistency (both receivers and normal parameters could have default values; as currently only ‘normal’ parameters can).

The main use case is that the Kotlin team recommends making functions that start coroutines as extensions on CoroutineScope, however if we want to start by default in some scope but still let the caller be able to select their own scope, the only way is to use regular parameters with default values, which breaks the recommended coding style.

Adhering to coroutine conventions does not worth changing language in such a dramatic way. Writing two functions is the perfect solution for now. Furthermore, using GlobalScope as default is not a good solution in general.

1 Like

I agree GlobalScope is not a good default. In my case I would like to default on Dispatchers.IO but still let the user use their own dispatcher if they want to.

1 Like