Home > Software design >  kotlin cast to Predicate
kotlin cast to Predicate

Time:12-20

I have the below error when i tried to cast to Predicate

java.lang.ClassCastException: class com.digital.test.WebClientErrorHandler$WebClientErrorHandlerBuilder$1 cannot be cast to class java.util.function.Predicate (com.digital.test.WebClientErrorHandler$WebClientErrorHandlerBuilder$1 is in unnamed module of loader 'app'; java.util.function.Predicate is in module java.base of loader 'bootstrap')

class WebClientErrorHandlerBuilder {
    private var functionalErrorPredicate: Predicate<HttpStatus>

    init {
        functionalErrorPredicate = (HttpStatus.BAD_REQUEST::equals as Predicate<HttpStatus>).or(HttpStatus.CONFLICT::equals).or(HttpStatus.NOT_FOUND::equals)
    }
}

CodePudding user response:

A Kotlin function is not a Predicate, so you cannot cast with the as operator.

You can use a SAM conversion to do this instead. The syntax looks like you are calling a constructor:

Predicate(HttpStatus.BAD_REQUEST::equals)

Alternatively, you can use Predicate.isEqual:

Predicate.isEqual<HttpStatus>(HttpStatus.BAD_REQUEST)

The or calls also takes Predicates, but there is an implicit conversion from function references to Java functional interfaces, so no problems there.

Finally, also consider writing this whole thing as a Kotlin function (HttpStatus) -> Boolean. Most of the time, you don't need anything special from the Java Predicate API when writing Kotlin.

class WebClientErrorHandlerBuilder {
    private var functionalErrorPredicate: (HttpStatus) -> Boolean = {
        it in setOf(
            HttpStatus.BAD_REQUEST,
            HttpStatus.CONFLICT,
            HttpStatus.NOT_FOUND
        )
    }
}
  • Related