Android, Mobile, Programming

Android Nuggets 3: Kotlin Symbol Processing

Kotlin Symbol Processing (KSP) is analogous to Java Annotation processing the difference being KSP is especially meant for Kotlin language. Annotations in programming languages are, similar to those in linguistics, structural elements containing additional or meta-information in the source code of a program. These are ignored by the computer when running the software, but they are important here for giving hints to compiler or interpreters. Java annotation processing works for most Kotlin constructs, wherein it uses some kind of interoperability  for Kotlin stuff to work. The Java annotation processor (kapt), before compilation, processes the Kotlin annotations, generates the Java stubs and feeds them to the Java compiler. Java annotation processing has some limitations for Kotlin, though, like, they cannot not deal with local functions and properties of Kotlin which do not exist in Java. Also, Java annotation processing does not help on kotlin multiplatform projects because it is primarily meant for Java.

If you want to enable KSP in your Kotlin project, the only changes required are to the project build file (also ensure you are on kotlin 1.5.0 +)

KSP is made for kotlin. It is attached to compiler and takes advantage of Kotlin incremental compilation and processes the annotations incrementally. KSP  is used for code generation from high level metadata. One major difference KSP and Java annotation processing is that, when it comes to Kotlin, kapt does type inference for all the Kotlin code as it needs to convert everything into Java stubs where as KSP does it only for the symbols that is it it is interested in, so it is faster and more efficient. In Java the incremental builds functionality was added later and the Java annotation processor was tweaked to allow incrementality with work from gradle inc, which meant that a single  annotation processor change would mean a full build whereas KSP is an integral part of Kotlin, part of API and hence can provide more information for incrementality and prevents unnecessary full builds.

Currently KSP is in alpha. It is experimentally being used in Room database and Moshi. It is soon to be integrated in AirBnb Android App.

You can create you own Kotlin preprocessors. A guide for the same: https://github.com/google/ksp/blob/main/docs/quickstart.md

https://unsplash.com/photos/HfWA-Axq6Ek?utm_source=unsplash&utm_medium=referral&utm_content=creditShareLink
Android Image Credits

Leave a Reply