Kotlin Symbol Processing API | Kotlin (2024)

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 two times faster.

  • To learn more about how KSP compares to kapt, check out why KSP.

  • To get started writing a KSP processor, take a look at the KSP quickstart.

Overview

The KSP API processes Kotlin programs idiomatically. KSP understands Kotlin-specific features, such as extension functions, declaration-site variance, and local functions. It 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 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. You can also substitute type arguments, specify variances, apply star projections, and mark nullabilities of types.

Another way to think of KSP is as a preprocessor framework of Kotlin programs. By considering KSP-based plugins as symbol processors, or simply processors, the data flow in a compilation can be described in the following steps:

  1. Processors read and analyze source programs and resources.

  2. Processors generate code or other forms of output.

  3. 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.

You can also get an overview of KSP in this video:

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 see at how a file might look from KSP's point of view:

KSFile packageName: KSName fileName: String annotations: List<KSAnnotation> (File annotations) declarations: List<KSDeclaration> KSClassDeclaration // class, interface, object simpleName: KSName qualifiedName: KSName containingFile: String typeParameters: KSTypeParameter parentDeclaration: KSDeclaration classKind: ClassKind primaryConstructor: KSFunctionDeclaration superTypes: List<KSTypeReference> // contains inner classes, member functions, properties, etc. declarations: List<KSDeclaration> KSFunctionDeclaration // top level function simpleName: KSName qualifiedName: KSName containingFile: String typeParameters: KSTypeParameter parentDeclaration: KSDeclaration functionKind: FunctionKind extensionReceiver: KSTypeReference? returnType: KSTypeReference parameters: List<KSValueParameter> // contains local classes, local functions, local variables, etc. declarations: List<KSDeclaration> KSPropertyDeclaration // global variable simpleName: KSName qualifiedName: KSName containingFile: String typeParameters: KSTypeParameter parentDeclaration: KSDeclaration extensionReceiver: KSTypeReference? type: KSTypeReference getter: KSPropertyGetter returnType: KSTypeReference setter: KSPropertySetter parameter: KSValueParameter

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:

interface SymbolProcessorProvider { fun create(environment: SymbolProcessorEnvironment): SymbolProcessor}

While SymbolProcessor is defined as:

interface SymbolProcessor { fun process(resolver: Resolver): List<KSAnnotated> // Let's focus on this fun finish() {} fun onError() {}}

A Resolver provides 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 the following:

class HelloFunctionFinderProcessor : SymbolProcessor() { // ... val functions = mutableListOf<KSClassDeclaration>() val visitor = FindFunctionsVisitor() override fun process(resolver: Resolver) { resolver.getAllFiles().forEach { it.accept(visitor, Unit) } } inner class FindFunctionsVisitor : KSVisitorVoid() { override fun visitClassDeclaration(classDeclaration: KSClassDeclaration, data: Unit) { classDeclaration.getDeclaredFunctions().forEach { it.accept(this, Unit) } } override fun visitFunctionDeclaration(function: KSFunctionDeclaration, data: Unit) { functions.add(function) } override fun visitFile(file: KSFile, data: Unit) { file.declarations.forEach { it.accept(this, Unit) } } } // ... class Provider : SymbolProcessorProvider { override fun create(environment: SymbolProcessorEnvironment): SymbolProcessor = TODO() }}

Resources

Supported libraries

The table includes a list of popular libraries on Android and their various stages of support for KSP:

Last modified: 22 January 2024

Kotlin Symbol Processing API | Kotlin (2024)

FAQs

Kotlin Symbol Processing API | Kotlin? ›

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 two times faster.

What is the difference between Kotlin symbol processing and Kapt? ›

KSP is more efficient and faster than KAPT because it directly processes Kotlin symbols rather than converting Kotlin code to Java bytecode. It reduces the overhead associated with the annotation processing step, leading to faster build times.

What is KSP in Kotlin? ›

Welcome, fellow developers, to the fascinating world of Kotlin Symbol Processing (KSP)! In this article, we will delve into the basics of KSP, exploring its features and benefits, and how it can simplify your Android development journey.

Can we use Kapt and KSP together? ›

You can run kapt and KSP alongside each other in your project while you're migrating, and the migration can be done module by module, library by library. Note: If a module has any kapt processors remaining, stubs are still generated in that module.

How to install KSP Kotlin? ›

  1. Step 1: Create new project. I used Android Studio Flamingo (2022.2.1 from March 2023) to create the project. ...
  2. Step 2: Add a KSP module. ...
  3. Step 3: Implement the KSP Processor. ...
  4. Step 4: Add KSP dependency into a shared module. ...
  5. Step 5: Build the project and verify that generated file is actually generated.
Oct 15, 2023

What is Gradle Kapt? ›

Kapt is the Kotlin Annotation Processing Tool, and it's in pretty good shape these days. If you want to be able to reference generated code from Kotlin, you need to use kapt. To do that, simply include the plugin in your build.gradle file with the line : apply plugin: 'kotlin-kapt' 2.

How different is Kotlin from Dart? ›

You can use both languages to build fully functional mobile applications. While Kotlin is primarily used for Android development, Dart is used alongside the Flutter framework to build functional User Interfaces for both Android and iOS applications. They also offer robust tooling and libraries for building mobile apps.

Why is KSP faster than Kapt? ›

Compared to kapt, annotation processors that use KSP can run up to twice as fast because KSP is not slowed down by creating intermediate stub classes and Gradle javac tasks 1. The same as with Annotation Processing, we will explore KSP by implementing an example project.

Is KSP good for learning? ›

Diving into this game allows a student to practice real-world applications of mathematics and physics while enjoying the challenge of building a successful spaceship! It's great practice to go right alongside our math or science programs here at A Grade Ahead!

Why is KSP useful? ›

It is a valuable tool for determining the direction that a reaction will proceed and the amount of unreacted products that remain.

What to use instead of Kapt? ›

KSP offers a more efficient and powerful alternative to Kapt (Kotlin Annotation Processing Tool), especially for larger projects. In this article, we'll explore how to transition from Kapt to KSP in your Gradle dependencies, showcasing its benefits and providing detailed examples in Kotlin.

What is Kapt used for? ›

Kapt stands for Kotlin Annotation Processing Tool. It is a command-line tool and builds plugins for the Kotlin programming language. It helps us to process annotations in Kotlin code during the build process. It works with build tools such as Gradle and Maven to analyze annotated code and generate additional code.

Does KSP support databinding? ›

Data Binding depends on KAPT, but KSP is the future

Being more complex than View Binding, Data Binding requires extra code generation and relies on KAPT. KAPT is in maintenance mode. JetBrains is keeping it up-to-date with recent Kotlin and Java releases but has no plans to implement new features.

What is the use of KSP in Kotlin? ›

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 two times faster.

Is KSP multiplatform? ›

Furthermore, since KSP is not tied to the JVM and Kotlin supports compilation targets like JS, we end up with a metaprogramming solution that is multi-platform.

How to add KSP to Gradle? ›

Here is a way to add ksp in android (version: giraffe) gradle library:
  1. First, click in build.gradle(project) and add [ id("com.google.devtools.ksp") version "1.8.10-1.0.9" apply false ] in plugin {}
  2. Next, click in build.gradle(module) to add this line [ id("com.google.devtools.ksp") ] in plugin{} .
May 3, 2022

What are the 2 types of comments in Kotlin? ›

There are two types of comments in Kotlin.
  • Single line comment.
  • Multi line comment.

What is annotation processing in Kotlin? ›

The idea behind annotation processing is quite simple: we define classes called processors that analyze our source code and generate additional files that typically also include code; however, these processors themselves don't modify existing code.

What is the difference between symbol table and debug symbols? ›

"Symbol" in the context of symbol tables refers to key-value pairs, and debug symbol is just special type of information used for debugging, and does not have anything to do with the primitive data type.

What is the difference between debounce and throttle in Kotlin? ›

Thus, debounce ignores all values except the last value and sends the last value only after a certain time has elapsed without receiving new values. Throttle remembers the last value and sends it every time after a certain interval, regardless of the number of values received during that period.

Top Articles
What the 100 nonprofits that raised the most money in 2020 indicate about charity today
How to make a budget as a student – TD Canada Trust
Aberration Surface Entrances
Dairy Queen Lobby Hours
Compare Foods Wilson Nc
Kathleen Hixson Leaked
Hannaford Weekly Flyer Manchester Nh
Missed Connections Inland Empire
Marist Dining Hall Menu
Displays settings on Mac
Cinepacks.store
Nichole Monskey
Was sind ACH-Routingnummern? | Stripe
Reddit Wisconsin Badgers Leaked
Discover Westchester's Top Towns — And What Makes Them So Unique
“In my day, you were butch or you were femme”
Belly Dump Trailers For Sale On Craigslist
Committees Of Correspondence | Encyclopedia.com
Costco Gas Foster City
Swgoh Turn Meter Reduction Teams
Dragger Games For The Brain
Tips and Walkthrough: Candy Crush Level 9795
Ecampus Scps Login
Smartfind Express Login Broward
Is Light Raid Hard
Pixel Combat Unblocked
Ihs Hockey Systems
Imagetrend Elite Delaware
Ilabs Ucsf
Armor Crushing Weapon Crossword Clue
A Small Traveling Suitcase Figgerits
Missouri State Highway Patrol Will Utilize Acadis to Improve Curriculum and Testing Management
Polk County Released Inmates
The best Verizon phones for 2024
Can You Buy Pedialyte On Food Stamps
NHL training camps open with Swayman's status with the Bruins among the many questions
Überblick zum Barotrauma - Überblick zum Barotrauma - MSD Manual Profi-Ausgabe
Tillman Funeral Home Tallahassee
Blackwolf Run Pro Shop
Acts 16 Nkjv
The Attleboro Sun Chronicle Obituaries
Windshield Repair & Auto Glass Replacement in Texas| Safelite
Dickdrainersx Jessica Marie
Centimeters to Feet conversion: cm to ft calculator
News & Events | Pi Recordings
Take Me To The Closest Ups
Euro area international trade in goods surplus €21.2 bn
Julies Freebies Instant Win
Nfhs Network On Direct Tv
Www Extramovies Com
Latest Posts
Article information

Author: Terrell Hackett

Last Updated:

Views: 5823

Rating: 4.1 / 5 (72 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Terrell Hackett

Birthday: 1992-03-17

Address: Suite 453 459 Gibson Squares, East Adriane, AK 71925-5692

Phone: +21811810803470

Job: Chief Representative

Hobby: Board games, Rock climbing, Ghost hunting, Origami, Kabaddi, Mushroom hunting, Gaming

Introduction: My name is Terrell Hackett, I am a gleaming, brainy, courageous, helpful, healthy, cooperative, graceful person who loves writing and wants to share my knowledge and understanding with you.