Kotlin:组合case语句,不允许访问成员变量

Kotlin:组合case语句,不允许访问成员变量,kotlin,Kotlin,在我的when语句中,我们有3个案例执行类似的操作 private fun bindValue(target: Activity) { val declaredFields = target::class.java.declaredFields for (field in declaredFields) { for (annotation in field.annotations) { when(annotation) {

在我的
when
语句中,我们有3个案例执行类似的操作

private fun bindValue(target: Activity) {
    val declaredFields = target::class.java.declaredFields

    for (field in declaredFields) {
        for (annotation in field.annotations) {

            when(annotation) {
                is ReflectSource -> {
                    field.isAccessible = true
                    field.set(target, annotation.value)
                }
                is ReflectBinary -> {
                    field.isAccessible = true
                    field.set(target, annotation.value)
                }
                is ReflectRuntime -> {
                    field.isAccessible = true
                    field.set(target, annotation.value)
                }
            }
        }
    }
}
所以我考虑合并它们,如下所示

private fun bindValue(target: Activity) {
    val declaredFields = target::class.java.declaredFields

    for (field in declaredFields) {
        for (annotation in field.annotations) {

            when(annotation) {
                is ReflectSource, is ReflectBinary, is ReflectRuntime -> {
                    field.isAccessible = true
                    field.set(target, annotation.value)
                }
            }
        }
    }
}
但是,它错误地指出,
注释
不可访问。为什么?我不能合并这3个案例陈述吗

更新 我的三门课如下

@Retention(AnnotationRetention.SOURCE)
@Target(AnnotationTarget.FIELD)
annotation class ReflectSource(val value: Int)

@Retention(AnnotationRetention.BINARY)
@Target(AnnotationTarget.FIELD)
annotation class ReflectBinary(val value: Int)

@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FIELD)
annotation class ReflectRuntime(val value: Int)
我不能合并这3个案例陈述吗

不,你不能。还记得它是如何工作的吗

is ReflectSource -> {
    field.isAccessible = true
    field.set(target, annotation.value)
}
案例:
annotation.value
隐藏编译器插入的强制转换,它实际上是
(作为ReflectSource的注释)。value

当您使用
时,编译器应该向哪个类插入cast,哪个类是ReflectSource,哪个类是ReflectBinary,哪个类是ReflectRuntime

原则上,编译器可以处理这个问题,但对于极少数情况,这会使语言描述和实现复杂化

减少重复的一个选择是

val value = when(annotation) {
    is ReflectSource -> annotation.value
    is ReflectBinary -> annotation.value
    is ReflectRuntime -> annotation.value
    else -> null
}
value?.let {
    field.isAccessible = true
    field.set(target, it)
}