How to use Android Support typedef annotations in kotlin?

匿名 (未验证) 提交于 2019-12-03 02:06:01

问题:

I develop Android applications and often use annotations as compile time parameter checks, mostly android's support annotations.

Example in java code:

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

I don't want to use enums because of their performance issues in Android. The automatic converter to kotlin just generates invalid code. How do I use the @IntDef annotation in kotlin?

回答1:

It is actually possible to use the @IntDef support annotation by defining your values outside of the annotation class as const vals.

Using your example:

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

Note that at this point the compiler seems to require the Long type for the @IntDef annotation instead of actual Ints.



回答2:

There's currently no way to achieve exactly this in Kotlin, since an annotation class cannot have a body and thus you cannot declare a constant in it which would be processed by IntDef. I've created an issue in the tracker: https://youtrack.jetbrains.com/issue/KT-11392

For your problem though, I recommend you use a simple enum.



回答3:

Use this:

companion object {     const val FLAG_PAGE_PROCESS = 0L//待处理     const val FLAG_PAGE_EXCEPTION = 1L//设备异常     const 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 } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!