android - 如何在 kotlin 中使用 Android Support typedef 注

我开发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 vals 来使用@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 类型,而不是实际的 Ints。

关于android - 如何在 kotlin 中使用 Android Support typedef 注解?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35976002/

相关文章:

java - Kotlin 获取类型为字符串

kotlin - 无需额外对象分配的数组/列表迭代

android - 如何像在 Swift 中一样从 Kotlin 中的函数返回多个值?

file - 在 Kotlin 中递归列出文件

input - 在 Kotlin 中读取控制台输入

properties - Kotlin 中是否有 didSet/willSet 模拟?

kotlin - 'by' 关键字在 Kotlin 中的作用是什么?

kotlin - Kotlin 中的交换函数

java - 为 Kotlin 创建 POJO 类

android - 类 'MyFirebaseMessagingService' 不是抽象的,也没有