我开发Android应用,经常使用注解作为编译时参数检查,主要是android的support annotations .
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
注解?
最佳答案
Edit: In case you miss the comments on the question or this answer, it's worth noting that the following technique compiles, but does not create the compile-time validation you would get in Java (which partially defeats the purpose of doing this). Consider using an enum class instead.
实际上可以通过将注释类的outside 值定义为const val
s 来使用@IntDef
支持注释。
使用您的示例:
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
注释的 Long
类型,而不是实际的 Int
s。
关于android - 如何在 kotlin 中使用 Android Support typedef 注解?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35976002/