我开发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;
    }
}

我不想使用enum,因为它们在安卓系统中存在性能问题.kotlin的自动转换器只会生成无效代码.如何在kotlin中使用@IntDef注释?

推荐答案

Edit:如果你错过了对问题或答案的 comments ,值得注意的是以下技巧,


It is actually possible to use the @IntDef support annotation by defining your values outside of the annotation class as const vals.

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
    }
}

请注意,在这一点上,编译器似乎需要@IntDef批注使用Long类型,而不是实际的Int.

Kotlin相关问答推荐

判断字符串是否除了.&" ",","@""""

Android Jetpack编写androidx.compose.oundation.lazy.grid.Items

如何在操作系统版本上正确获取Room数据库的路径>;=26 sdk?

kotlin - 挂起简单方法调用链时可能存在冗余分支

合并状态流

在 map 中查找键与在 kotlin 中查找 firstOrNull

有没有一种简单的方法可以将数组/列表中的每个元素相互相乘 - Kotlin?

JavaFX - 你如何在 Kotlin 中使用 MapValueFactory?

将子元素放在一个列表中

Kotlin 无法找到或加载主类

在 Kotlin 中使用 @Parcelize 注释时如何忽略字段

将 Kotlin 类属性设置器作为函数引用

有没有办法在spring webflux和spring data react中实现分页

Android Room - error: Cannot figure out how to save this field into database

Kotlin 的 Double.toInt() 中使用了哪种方法,舍入还是截断?

如何为 Java 调用者声明返回类型为void的 Kotlin Lambda?

spring.config.location 在 Spring Boot 2.0.0 M6 上不起作用

Mocked suspend函数在Mockito中返回null

如何计算Kotlin中的百分比

如何在 Gradle Kotlin DSL 中使用来自 gradle.properties 的插件版本?