Context parameters
Context parameters allow functions and properties to declare dependencies that are implicitly available in the surrounding context.
With context parameters, you don't need to manually pass around values, such as services or dependencies, that are shared and rarely change across sets of function calls.
To declare context parameters for properties and functions, use the context
keyword followed by a list of parameters, with each parameter declared as name: Type
. Here is an example with a dependency on the UserService
interface:
You can use _
as a context parameter name. In this case, the parameter's value is available for resolution but is not accessible by name inside the block:
Context parameters resolution
Kotlin resolves context parameters at the call site by searching for matching context values in the current scope. Kotlin matches them by their type. If multiple compatible values exist at the same scope level, the compiler reports an ambiguity:
Restrictions
Context parameters are in continuous improvement, and some of the current restrictions include:
Constructors can't declare context parameters.
Properties with context parameters can't have backing fields or initializers.
Properties with context parameters can't use delegation.
Despite these restrictions, context parameters simplify managing dependencies through simplified dependency injection, improved DSL design, and scoped operations.
How to enable context parameters
To enable context parameters in your project, use the following compiler option in the command line:
Or add it to the compilerOptions {}
block of your Gradle build file:
This feature is planned to be stabilized and improved in future Kotlin releases. We would appreciate your feedback in our issue tracker YouTrack.