如何在 kotlin 中使用 Android Support typedef 注释? [英] How to use Android Support typedef annotations in kotlin?
问题描述
我开发Android应用程序,经常使用注解作为编译时参数检查,主要是android的支持注解.
java 代码示例:
公共类测试{@IntDef({Speed.SLOW,Speed.NORMAL,Speed.FAST})公共@interface 速度{public static final int SLOW = 0;public static final int NORMAL = 1;public static final int FAST = 2;}@速度私有int速度;public void setSpeed(@Speed int speed){this.speed = 速度;}}
我不想使用枚举,因为它们在 Android 中存在性能问题.kotlin 的自动转换器只会生成无效代码.如何在 kotlin 中使用 @IntDef
注释?
如果您错过了对问题或此答案的评论,请注意以下技术编译,但不会创建您将获得的编译时验证Java(部分违背了这样做的目的).考虑使用 enum班级相反.
<小时>
实际上可以通过将注释类的外部值定义为 const val
s 来使用 @IntDef
支持注释.
使用您的示例:
import android.support.annotation.IntDef公共类测试{伴生对象{@IntDef(慢,正常,快)@Retention(AnnotationRetention.SOURCE)注释类 Speed常量值慢 = 0Lconst val 正常 = 1L常量值快速 = 2L}@速度私有 lateinit var 速度:长公共乐趣 setSpeed(@Speed speed: Long) {this.speed = 速度}}
请注意,此时编译器似乎需要 @IntDef
注释的 Long
类型,而不是实际的 Int
.>
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?
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.
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.
这篇关于如何在 kotlin 中使用 Android Support typedef 注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!