如何在Kotlin中使用Android支持的typedef注释?
我开发Android应用程序,并经常将注释用作编译时参数检查,大部分是android的支持注释.
I develop Android applications and often use annotations as compile time parameter checks, mostly android's 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
批注?
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?
编辑:如果您错过了对该问题或此答案的评论,请注意,以下技术可以编译, 但是 not 不会创建您将获得的编译时验证 Java(部分挫败了这样做的目的).考虑使用枚举 课 代替.
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
支持注释.
It is actually possible to use the @IntDef
support annotation by defining your values outside of the annotation class as const val
s.
使用您的示例:
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
}
}
请注意,此时,编译器似乎需要Long
类型的@IntDef
注释,而不是实际的Int
s.
Note that at this point the compiler seems to require the Long
type for the @IntDef
annotation instead of actual Int
s.