可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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 val
s.
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 Int
s.
回答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 }