Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am having very annoying issue that i can't solve, and i guess i am missing something really straight forward, because i already have working code in Java.

Basically what i have is this:

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])
    }
}

The code is really straight forward, but from some reason Kotlin is complaining about it, error that i get is this:

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

And this is working java code:

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

Any experienced Kotlin person who knows workaround for this error ? I have seen some other people had similar issues, but i can not fix this based on answers that i seen.

like image 813
Sahbaz Avatar asked Jan 26 '26 05:01

Sahbaz


1 Answers

From docs:

< 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.

To fix your error, you need to specify generic type explicitly, because Kotlin compiler can't infer it from context:

predicates.add(builder.equal(root.get</* type of criteria.value */>(criteria.key), criteria.value))
like image 119
ardenit Avatar answered Jan 28 '26 11:01

ardenit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!