【问题标题】:How to implement Java's @StringDef in Kotlin如何在 Kotlin 中实现 Java 的 @StringDef
【发布时间】:2018-10-04 10:28:35
【问题描述】:

我的 Kotlin 项目需要 Java @StringDef 注解。

不幸的是,这似乎很困难。我在这里找到了讨论:

https://discuss.kotlinlang.org/t/intdef-and-stringdef-not-being-checked-at-compile-time/7029/3

据我所知,这可能是 Lint 问题。不进行编译时检查。没有提出任何建议。我可以添加任何字符串作为参数。

我最终只用我的常量创建了一个 Java 类。

public class AppFeatures {

    /** @hide */
    @StringDef({USER, USER_ACCOUNT})
    @Retention(RetentionPolicy.SOURCE)
    public @interface AppFeature {}

    /** Constants for certain features */
    public static final String USER = "user";
    public static final String USER_ACCOUNT = "user.account";
}

使用 Kotlin 等效项时,没有编译时检查或建议。

我尝试了类似的方法但没有成功:

@StringDef(USER, USER_ACCOUNT)
@Retention(AnnotationRetention.SOURCE)
annotation class AppFeature

const val USER = "user"
const val USER_ACCOUNT = "user.account"

那么我该如何在 Kotlin 中实现呢?

【问题讨论】:

标签: kotlin annotations lint


【解决方案1】:

@StringDef 现在如果您在伴随对象中定义它就可以工作。例如:

public class Test {

    companion object {

         @StringDef(SLOW, NORMAL, FAST)
         @Retention(AnnotationRetention.SOURCE)
         annotation class Speed

         const val SLOW = "slow"
         const val NORMAL = "normal"
         const val FAST = "fast"
    }

    @Speed
    private lateinit var speed: String

    public fun setSpeed(@Speed speed: String) {
        this.speed = speed
    }
}

此代码示例大部分来自:
https://newbedev.com/how-to-use-android-support-typedef-annotations-in-kotlin

还请考虑改用 Kotlin 枚举类,这将允许您为每个枚举指定字符串值:
https://kotlinlang.org/docs/enum-classes.html

对于运行 Dalvik 的手机来说,枚举是一个内存问题,但它基本上已被 ART(Android 运行时机器)取代。再加上即使是较贫穷国家的人们也拥有相当强大的手机,而且 Proguard 现在可以比以往更好地优化代码,可以肯定地说 Enums 不再导致性能问题。更多关于这里的信息:
https://www.ericthecoder.com/2019/10/07/kotlin-or-java-enum-classes-the-good-the-bad-and-the-ugly/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-23
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    • 2021-09-02
    • 2021-09-03
    • 2017-10-02
    • 1970-01-01
    相关资源
    最近更新 更多