为什么第14行和第21行没有编译(对于我的Kotlin函数)?

7lrncoxx  于 2023-02-19  发布在  Kotlin
关注(0)|答案(1)|浏览(141)

我有一个名为collectCustomizerFunctions的函数,它应该创建一个指定类及其子类的所有函数的MutableList<KCallable<*>>,这些类和子类用CustomizerFunction注解。
递归地,customizerFunsMutableList<KCallable<*>>)应该添加所有的“自定义函数”。
当我尝试构建Gradle项目时,它失败了,但有两个例外:

e: collectCustomizerFuns.kt:14:33 Type inference failed. The value of the type parameter T should be mentioned in input types (argument types, receiver type or expected type). Try to specify it explicitly.

e: collectCustomizerFuns.kt:21:30 Type mismatch: inferred type is Any but CapturedType(*) was expected

下面是我的代码:

3  | import kotlin.reflect.KClass
4  | import kotlin.reflect.KCallable
5  | import kotlin.reflect.full.allSuperclasses
6  |
7  | @Utility
8  | public tailrec fun <T: Any> collectCustomizerFuns(
9  |        specClass: KClass<T>,
10 |        customizerFuns: MutableList<KCallable<*>>
11 | ): Unit {
12 |         // add annotated functions of this class
13 |         for (member in specClass.members) {
14 |                 if (CustomizerFunction::class in member.annotations) {     <--- ERROR
15 |                         customizerFuns.add(member)
16 |                 } else {}
17 |         }   
18 | 
19 |         // add annotated functions of all super-classes
20 |         for (superclass in specClass.allSuperclasses) {
21 |                 collectCustomizerFuns<Any>(superclass, customizerFuns)     <--- ERROR                                                                                                                         
22 |         }   
23 | }

我一直在尝试修复这些错误有一段时间了,现在,并将感谢任何帮助!
此外,请提供任何建设性的批评,你想关于这个功能,这将帮助很大!

qnzebej0

qnzebej01#

对于第一个错误,member.annotations返回List<Annotation>,您必须获取这些注解的实际类。
对于第二个错误,删除调用collectCustomizerFuns的类型,让Kotlin自己推断类型:)。
所以试试这个:

public tailrec fun <T: Any> collectCustomizerFuns(
    specClass: KClass<T>,
    customizerFuns: MutableList<KCallable<*>>
) {
    // add annotated functions of this class
    for (member in specClass.members) {
        if (CustomizerFunction::class in member.annotations.map { it.annotationClass }) {
            customizerFuns.add(member)
        } else {
        }
    }

    // add annotated functions of all super-classes
    for (superclass in specClass.allSuperclasses ) {
        collectCustomizerFuns(superclass, customizerFuns)
    }
}

顺便说一下,您可以从方法签名中删除Unit

相关问题