如何在Kotlin中使用StringDef或IntDef?

时间:2018-10-17 01:29:30

标签: android kotlin annotations

引用https://developer.android.com/reference/android/support/annotation/StringDef https://developer.android.com/reference/android/support/annotation/IntDef

我可以轻松创建编译验证,该验证将String参数限制为特定类型的String(在Java中)

例如

import android.support.annotation.StringDef;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.SOURCE;

@Retention(SOURCE)
@StringDef({
    "allow_one",
    "okay_two"
})
public @interface AllowedString { }

如果我有

class TestAnnotation(@AllowedString private val name: String) {
    fun printName(@AllowedString name: String) {}
}

当我编码时

val testAnnotation = TestAnnotation("not_allowed")

Android Studio将在not_allowed上标记错误,因为它不在列表中。

如果我将AllowedString注释界面转换为Kotlin,如下所示,它将不再起作用。为什么?

import android.support.annotation.StringDef
import java.lang.annotation.Retention
import java.lang.annotation.RetentionPolicy.SOURCE

@Retention(SOURCE)
@StringDef("allow_one", "okay_two")
annotation class AllowedString

为什么?

0 个答案:

没有答案
相关问题