如何在Kotlin中使用Android支持的typedef注释? [英] How to use Android Support typedef annotations in kotlin?

查看:242
本文介绍了如何在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 vals.

使用您的示例:

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 Ints.

这篇关于如何在Kotlin中使用Android支持的typedef注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆