【发布时间】:2022-01-25 01:32:47
【问题描述】:
这个问题的主要目标是了解实现以及为什么会这样。当然,它的解决方案或解决方法也将受到高度赞赏......
举个例子:
enum class SomeEnum(val customProp: String) {
FOO("fooProp"),
BAR("barProp");
}
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.SOURCE)
annotation class TheAnnotation(
val targetValue: String
)
@TheAnnotation(targetValue = SomeEnum.FOO.customProp)
fun testFun() {
}
编译导致如下错误:
SomeEnum.kt: (14, 30): 注解参数必须是编译时常量
由于显而易见的原因,注释值(以及其他值)必须是编译时常量,这在许多不同方面都有意义。我不清楚的是,为什么 customProp 不被编译器视为常量。
如果枚举被定义为有限的、封闭的信息集,在我的理解中,它们应该只在编译时可变,也就是“编译时常量”。对于在 Kotlin 中以某种方式在运行时可以修改枚举的不太可能的情况,这也可以回答这个问题。
附录:
枚举值(例如SomeEnum.FOO)实际上被视为编译时常量。证明是,以下稍微改变的 sn-p 编译:
enum class SomeEnum(val customProp: String) {
FOO("fooProp"),
BAR("barProp");
}
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.SOURCE)
@MustBeDocumented
annotation class TheAnnotation(
val targetValue: SomeEnum
)
@TheAnnotation(targetValue = SomeEnum.FOO)
fun testFun() {
}
【问题讨论】:
-
合理怀疑可能是
Foo(if System.currentTimeMillis() % 2L == 0L) "hello" else "bye")。我还没有尝试过,因为我现在在手机上,但如果编译成功,那么你就有答案了