Can context receivers be used with extension functions? If so, how?

Android interview question for Advanced practice.

Answer

Yes, by defining the context receiver for the function. It is placed before the fun keyword, affecting the scope of the extension function.

Explanation

Yes, context receivers can be used with extension functions. The context receiver is specified before the fun keyword, making the context receiver available within the scope of that extension function. This allows the extension function to implicitly access members of the context receiver. For example: context(MyContext) fun String.myExtensionFunction() { / access MyContext members here / }. Options A, B, and C describe incorrect ways or state it's not possible.

Related Questions