Search code examples
kotlinkotlinx.coroutines

Why is CoroutineScope.launch and Coroutine.async are extension functions instead of a member function of CoroutineScope?


The title states my question.

What is exactly the reason why CoroutineScope.launch and Coroutine.async are just extension functions of CoroutineScope instead oa a member function?

What benefits does it provide?

I am asking because maybe the reason behind this design could be helpful in designing things in the future too.

Thank in advance.


Solution

  • launch and async are coroutine builders, but they aren't the only ones: look in integration modules for future (and another future), publish, the RxJava 2 builders etc. Obviously those can't be members of CoroutineScope, so why should launch and async be?

    In addition, by being extension functions you know they don't rely on any CoroutineScope privates (well, they could rely on internals since they are in the same module).