Kotlin Symbol Processing API
Kotlin Symbol Processing (KSP) is an API that you can use to develop lightweight compiler plugins. KSP provides a simplified compiler plugin API that leverages the power of Kotlin while keeping the learning curve at a minimum. Compared to KAPT, annotation processors that use KSP can run up to 2x faster.
The KSP API processes Kotlin programs idiomatically. KSP understands Kotlin-specific features, such as extension functions, declaration-site variance, and local functions. KSP also models types explicitly and provides basic type checking, such as equivalence and assign-compatibility.
The API models Kotlin program structures at the symbol level according to Kotlin grammar. When KSP-based plugins process source programs, constructs like classes, class members, functions, and associated parameters are easily accessible for the processors, while things like if blocks and for loops are not.
Conceptually, KSP is similar to KType in Kotlin reflection. The API allows processors to navigate from class declarations to corresponding types with specific type arguments and vice-versa. Substituting type arguments, specifying variances, applying star projections, and marking nullabilities of types are also possible.
Another way to think of KSP is as a pre-processor framework of Kotlin programs. If we refer to KSP-based plugins as symbol processors, or simply processors, then the data flow in a compilation can be described in the following steps:
Processors read and analyze source programs and resources.
Processors generate code or other forms of output.
The Kotlin compiler compiles the source programs together with the generated code.
Unlike a full-fledged compiler plugin, processors cannot modify the code. A compiler plugin that changes language semantics can sometimes be very confusing. KSP avoids that by treating the source programs as read-only.
How KSP looks at source files
Most processors navigate through the various program structures of the input source code. Before diving into usage of the API, let's look at how a file might look from KSP's point of view:
This view lists common things that are declared in the file--classes, functions, properties, and so on.
SymbolProcessorProvider: The entry point
KSP expects an implementation of the
SymbolProcessorProvider interface to instantiate
SymbolProcessor is defined as:
SymbolProcessor with access to compiler details such as symbols. A processor that finds all top-level functions and non-local functions in top-level classes might look something like this:
The table below includes a list of popular libraries on Android and their various stages of support for KSP. If your library is missing, please feel free to submit a pull request.
|Library||Status||Tracking issue for KSP|
|Auto Factory||Not yet supported||Link|
|Dagger||Not yet supported||Link|
|Hilt||Not yet supported||Link|
|Glide||Not yet supported||Link|
|DeeplinkDispatch||Not yet supported||Link|