无法在 Kotlin 中添加条件 api 谓词,出现 Type interface failed 错误

Can not add criteria api predicate in Kotlin, getting Type interface failed error

我有一个非常烦人的问题,我无法解决,我想我错过了一些非常直接的东西,因为我已经在 Java.

中有了工作代码

基本上我有的是:

class ConfigurationSpecification(
        private var list: MutableList<SearchCriteria> = mutableListOf()
) : Specification<Configuration> {
    override fun toPredicate(root: Root<Configuration>, query: CriteriaQuery<*>, builder: CriteriaBuilder): Predicate? {
        val predicates: MutableList<Predicate> = mutableListOf()

        for (criteria in list) {
            if (criteria.operation == "EQUALS") {
                predicates.add(builder.equal(root.get(criteria.key), criteria.value)) <- NOT WORKING root.get(criteria.key) this is making issue
            }
        }

        return builder.and(predicates[0])
    }
}

代码真的很简单,但出于某种原因 Kotlin 抱怨它,我得到的错误是这样的:

Error:(19, 51) Kotlin: Type inference failed: Not enough information to infer parameter Y in fun get(p0: String!): Path! Please specify it explicitly.

这是有效的 java 代码:

predicates.add(builder.equal(root.get(criteria.getKey()), criteria.getValue())); <- working with Java

任何有经验的 Kotlin 人员知道此错误的解决方法?我看到其他人有类似的问题,但我无法根据我看到的答案解决这个问题。

来自文档:

< Y> Path< Y> get(String attributeName)

Create a path corresponding to the referenced attribute.

Note: Applications using the string-based API may need to specify the type resulting from the get operation in order to avoid the use of Path variables.

要修复您的错误,您需要明确指定泛型类型,因为 Kotlin 编译器无法从上下文中推断它:

predicates.add(builder.equal(root.get</* type of criteria.value */>(criteria.key), criteria.value))