Kotlin Annotation IntDef

Strange thing, but this question comes in search before the same with right answer

Copying it here:

import android.support.annotation.IntDef
public class Test {

    companion object {

         @IntDef(SLOW, NORMAL, FAST)
         @Retention(AnnotationRetention.SOURCE)
         annotation class Speed

         const val SLOW = 0
         const val NORMAL = 1
         const val FAST = 2
    }

    @Speed
    private var speed: Int=SLOW

    public fun setSpeed(@Speed speed: Int) {
        this.speed = speed
    }
}

If you are calling setMeasureText from Java you can get it to work by creating your IntDef in Java too

// UnitType.java
@Retention(RetentionPolicy.SOURCE)
@IntDef({MeasureText.UNIT_KG, MeasureText.UNIT_LB, MeasureText.UNIT_NONE})
public @interface UnitType {}

h/t Tonic Artos

You will also need to update your companion object to make your values longs and publicly accessible

companion object{
    const val UNIT_NONE = -1L
    const val UNIT_KG = 1L
    const val UNIT_LB = 0L
}

My preferred way to use IntDef with Kotlin is to use top-level declarations:

package com.example.tips


const val TIP_A = 1
const val TIP_B = 2
const val TIP_C = 3

@IntDef(TIP_A, TIP_B, TIP_C)
@Retention(AnnotationRetention.SOURCE)
annotation class TipId


class TipsDataProvider {

    fun markTip(@TipId tipId: Int) {
    ...
    }
}

No extra class or object required! More info about top-level declarations here.


As of Kotlin 1.0.3, the @IntDef annotation is not supported, but support is planned for later versions.

The Kotlin way of making these compile time checks is to use an enum class instead of a series of Int constants.