DEV Community

Cover image for Android KSP guide for dummies by a Dummy: Part 1
Aniket Bhoite
Aniket Bhoite

Posted on

Android KSP guide for dummies by a Dummy: Part 1

KSP, Kotlin Symbol Processing is answer to annotation processing for Kotlin by google. It replaces older Kapt(Kotlin Annotations Processing) which was slower and less flexible to support native features of Kotlin language.

KSP (or Kapt) is useful for meta-programming and writing repetitive code. We analyse code and use code to write code

Problem to solve

To demonstrate let's take a problem to solve using KSP. In an average app there are maybe more than one analytic tools that requires event params in different formats. For example firebase Analytics SDK require params in key-value bundle but our own custom Analytic SDK accepts params in key-value pair HashMap

For that we need to create class with two functions, one returning attributes in Bundle and 2nd in HashMap for every event

    fun getBundleOfParamsForFirebase(): Bundle {
        val bundle = Bundle().apply {
            putString(paramName1, param1)
            putString(paramName2, param2)
        }
        return bundle
    }

    fun getHashMapOfParamsForCustomAnalytics(): HashMap<*, *>? {
        val map = HashMap<String, Any>().apply { 
            put(paramName1, param1)
            put(paramName1, param1)
        }
        return map
    }
Enter fullscreen mode Exit fullscreen mode

This looks simple and doable manually but as number of params and number events increases it becomes cumbersome and error prone

Let's look at a solution, in this we will only create EventParams class with annotation based on which our Event class will get created. for ex.

    @MyEvent
    data class TicketBookClickedParams(
        val eventName: String,
        val screenName: String,
        val ticketNumber: String,
        val ticketAmount: String
    )
Enter fullscreen mode Exit fullscreen mode

KSP processor will recognise all data classes Annotated with @MyEvent annotation and generate Event class for it.

This guide is further divided into parts, feel free to jump around if you like.

  1. Intro
  2. KSP Gradle setup & Processor's first log: Part 2 (link)
  3. Generate the code using KSP : Part 3 (link)
  4. Using KSP output in app: Part 4 (link)

Title & disclaimer

This series is for devs who have never used or created anything using KSP. This will not cover advance & complex use cases. This example will not have any kind of design pattern. We will go with straight forward approach which is not recommended for production apps. Thatโ€™s why title is guide for dummies by a Dummy(a or the Dummy depending upon whom you ask.)

If anyone finds any mistakes or have any suggestion please feel free to add comment.

Links:
GitHub Repo : https://github.com/aniketbhoite/ksp-my-event
Google KSP Doc: https://github.com/google/ksp
KotlinLang KSP Doc: https://kotlinlang.org/docs/ksp-overview.html

Top comments (0)