BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News KSP2 Aims to Improve Kotlin Meta-Programming, Adds Support for the K2 Kotlin Compiler

KSP2 Aims to Improve Kotlin Meta-Programming, Adds Support for the K2 Kotlin Compiler

Currently available in preview, KSP 2.0, the evolution of Kotlin Symbol Processing (KSP), introduces a new architecture aimed at resolving some limitations in KSP 1.0 and adds support for the new K2 Kotlin compiler, explain Google software engineers Ting-Yuan Huang and Jiaxiang Chen.

While KSP1 is implemented as a compiler plugin, KSP2 is an independent library that can be run without setting up the compiler and with complete control of its lifecycle. This makes it easier to call KSP programmatically and set breakpoints in KSP processors in an easy way, say Huang and Chen. The following snippet shows how you can configure KSP2 and execute it to process a list of symbols:

val kspConfig = KSPJvmConfig.Builder().apply {
  // All configurations happen here.
}.build()
val exitCode = KotlinSymbolProcessing(kspConfig, listOfProcessors, kspLoggerImpl).execute()

Another notable difference in KSP2 is it uses the Kotlin K2 compiler, still in beta, to process source code. You can however use KSP with K1, if you prefer, by setting the languageVersion setting in gradle.properties.

Additionally, KSP2 aims to address a shortcoming in KSP1 which leads to the same source files being potentially compiled multiple times. Leveraging its integration with K2, KSP2 tries to align to how K2 compiles files to process them only once, which will improve performance.

KSP2 also introduces several behavior changes to improve developer productivity, as well as debuggability and error recovery.

The new KSP preview can be enabled in KSP 1.0.14 or newer using a flag in gradle.properties:

ksp.useKSP2=true

KSP is an API that enables the creation of plugins to extend the Kotlin compiler. It understands Kotlin language features like extension functions, declaration-site variance, and local functions in a compiler-independent way.

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 accessible for the processors, while things like if blocks and for loops are not.

This makes KSP-based plugins less fragile than plugins built on top of kotlinc, which have more power but depend strictly on the compiler version.

About the Author

Rate this Article

Adoption
Style

BT