Kotlin注释IntDef

我有这个代码示例:

class MeasureTextView: TextView { constructor(context: Context?) : super(context) constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) companion object{ val UNIT_NONE = -1 val UNIT_KG = 1 val UNIT_LB = 0 } fun setMeasureText(number: Float, unitType: Int){ val suffix = when(unitType){ UNIT_NONE -> { EMPTY_STRING } UNIT_KG -> { KG_SUFIX } UNIT_LB -> { LB_SUFIX } else -> throw IllegalArgumentException("Wrong unitType passed to formatter: MeasureTextView.setMeasureText") } // set the final text text = "$number $suffix" } } 

我希望能够在编译时使用自动完成功能和IntDef注释,所以当我调用setMeasureText(...) ,静态变量显示为这个方法参数的选项。

我已经搜索了这个,我找不到如果Kotlin支持这种java风格的注释(例如intdef)。 所以我已经尝试过了,并为此做了一个注释,但是它不会以自动完成的方式显示。

我的问题: – Kotlin支持Java注释IntDef(最新版本)

  • 如果是这样,我怎么能在Android Studio IDE中打开(如果它工作,我不能让编译器建议它)。

  • 如果不是的话,是否有任何Kotlin方式使这个编译时间检查

从Kotlin 1.0.3开始, @IntDef注解不被支持,但是为更高版本计划提供支持。

Kotlin做这些编译时检查的方法是使用一个enum class而不是一系列的Int常量。

奇怪的事情,但这个问题在正确的答案之前进入搜索

在这里复制:

 import android.support.annotation.IntDef public class Test { companion object { @IntDef(SLOW, NORMAL, FAST) @Retention(AnnotationRetention.SOURCE) annotation class Speed const val SLOW = 0L const val NORMAL = 1L const val FAST = 2L } @Speed private lateinit var speed: Long public fun setSpeed(@Speed speed: Long) { this.speed = speed } } 

如果从Java调用setMeasureText ,则可以通过在Java中创建IntDef来使其工作

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

h / t Tonic Artos

您还需要更新伴随对象,以使您的值长久并可公开访问

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