如何在kotlin中使用Android支持typedef注释?

我开发的Android应用程序,经常使用注释作为编译时间参数检查,主要是Android的支持注释 。

java代码示例:

public class Test { @IntDef({Speed.SLOW,Speed.NORMAL,Speed.FAST}) public @interface Speed { public static final int SLOW = 0; public static final int NORMAL = 1; public static final int FAST = 2; } @Speed private int speed; public void setSpeed(@Speed int speed) { this.speed = speed; } } 

我不想使用枚举,因为他们在Android的性能问题。 自动转换为kotlin只会产生无效的代码。 如何在kotlin中使用@IntDef批注?

实际上,可以使用@IntDef支持注释,方法是将注释类之外的值定义为const val

用你的例子:

 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 } } 

请注意,此时编译器似乎需要@IntDef注释的Longtypes而不是实际的Int

目前还没有办法在Kotlin中实现这个function,因为注释类不能有一个主体,因此你不能在其中声明一个由IntDef处理的IntDef 。 我在跟踪器中创建了一个问题: https : //youtrack.jetbrains.com/issue/KT-11392

对于你的问题,但我建议你使用一个简单的枚举。

用这个:

 companion object { const val FLAG_PAGE_PROCESS = 0L//待处理const val FLAG_PAGE_EXCEPTION = 1L//设备exceptionconst val FLAG_PAGE_UNCHECKED = 2L//未审核const val FLAG_PAGE_AUDIT = 3L//统计val FLAG_PAGE = "FLAG_PAGE" fun newInstance(@FlagPageDef flagPage: Int): RepairFormsListFragment { val fragment = RepairFormsListFragment() val args = Bundle() fragment.arguments = args return fragment } @Retention(AnnotationRetention.SOURCE) @IntDef(FLAG_PAGE_PROCESS, FLAG_PAGE_EXCEPTION, FLAG_PAGE_UNCHECKED, FLAG_PAGE_AUDIT) annotation class FlagPageDef }