Creating library using annotation processing and Kotlin Poet

Usecase

interface Callback {
fun success(response: String, code: Int)
fun error(errorCode: Int)
}
someClass.setCallback(object : Callback {
override fun success(response: String, code: Int) {
}
override fun error(errorCode: Int) {
}
})
final class PimpedCallback : Callback {
private var _success: ((String, Int) -> Unit)? = null
private var _error: ((Int) -> Unit)? = null override fun success(arg0: String, arg1: Int) {
_success?.invoke(arg0, arg1)
}
fun success(receiver: (String, Int) -> Unit): Unit {
_success = receiver
}
override fun error(arg0: Int) {
_error?.invoke(arg0)
}
fun error(receiver: (Int) -> Unit): Unit {
_error = receiver
}
}
fun setListener(init: PimpedCallback.() -> Unit) {
callBack = PimpedCallback().apply(init)
}
someClass.setListener {
success { response, code -> processResponse(response, code) }
error { _ -> }
}

Annotation processing

package com.trembita.annotation @Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.CLASS)
annotation class Trembita
class TrembitaProcessor : AbstractProcessor() {}

Kotlin Poet

  • field with lambda
  • function realisation
  • field initialisation function

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store