在 kotlin 中定义 StringDef

Ada*_*dam 6 android annotations kotlin

我正在尝试在 kotlin 中定义一个 StringDef:

@Retention(AnnotationRetention.SOURCE)
@StringDef(NORTH, SOUTH)
annotation class FilterType {

    companion object {
        const val NORTH = "NORTH"
        const val SOUTH = "SOUTH"
    }
}
Run Code Online (Sandbox Code Playgroud)

我认为上面的代码有问题。

// I can send anything to this method, when using my kotlin stringDef
private fun takeString(@DirectionJava.Direction filterType: String) {
Run Code Online (Sandbox Code Playgroud)

我想要与下面的java等效的kotlin:

public class DirectionJava {

    public static final String NORTH = "NORTH";
    public static final String SOUTH = "SOUTH";

    @Retention(RetentionPolicy.SOURCE)
    @StringDef({
            NORTH,
            SOUTH,
    })
    public @interface Direction {

    }
}
Run Code Online (Sandbox Code Playgroud)

从 kotlin 调用 java 定义的 StringDef 工作

// This works as expected, the Java-written string def 
// restricts what I can pass to this method
private fun takeString(@DirectionJava.Direction filterType: String) {
Run Code Online (Sandbox Code Playgroud)

我哪里出错了,你如何在 Kotlin 中定义 StringDef?

ami*_*phy 7

根据jetbrains 问题Lint在 kotlin 中检查枚举注释的插件正在开发中并且还不稳定。检查 android 支持注释,如@Nullable, @StringRes, @DrawableRes, @IntRange, ...(用 java 编写)工作正常,用户定义的枚举注释未正确检查。所以,似乎我们应该在java中定义它们然后在kotlin中使用。

  • 不幸的是,Kotlin 中没有关于这个主题的改进的证据。因此 lint 不会检查带注释的用户定义的 StringDef 等变量的值。 (3认同)