Skip to main content

Kotlin, IntDef, and Android libraries

Lately I’ve been investing time into Kotlin. Tonight, I was particularly interested in its utility for Android libraries.

IntDef

Update: Actually, lint doesn’t quite interoperate properly with Kotlin. So, while the following gets IntDefs and the related support annotations working 90%, you have to do things a little different, which I’ve outlined here.

First up is how to use the support library’s IntDef annotation in Kotlin. This is especially important for library development since it is considered best practice to avoid enum usage for Android development. I don’t really want to go into the arguments about this practice, this is just how to use it. As it turns out, this is pretty easy. In Kotlin, using IntDef looks like this;

companion object {
    const val YEAR = 1L
    const val MONTH = 2L
    const val WEEK = 3L
    const val DAY = 4L
}

@IntDef(YEAR, MONTH, WEEK, DAY)
annotation class TimePeriod

and the same code in Java looks like this:

public static final long YEAR = 1l
public static final long MONTH = 2l
public static final long WEEK = 3l
public static final long DAY = 4l

@IntDef({ YEAR, MONTH, WEEK, DAY })
public @interface TimePeriod {}

Listeners

If I am to move to using Kotlin for my librares, one of the things I was most interested in was whether I could write the library to be indistinguishably different to a regular Android Java library. For now I think this is true, you just have to keep using listener objects;

var listener: SomethingHappenedListener? = null

interface SomethingHappenedListener {
    fun somethingHappened(foo: Bar)
}

and not be tempted to use lambdas:

var listener: ((foo: Bar) -> Unit)? = null

However, this issue is specific to only single method listeners.

Moving on

In the future, sometime, I am curious about the opportunity to use Kotlins DSL utility as a compliment to a libraries regular API, though this would be Kotlin specific. Hmm, this brings to mind that I actually haven’t yet checked to see what the DSLs look like in Java land. Well I am sure that IntelliJ will cook something up that compiles.

Comments