0

I am using the Quarkus framework and have an ApplicationScoped bean that implements an interface with a method with the signature of loadRatingByUserIdAndVehicleId(userId: Long, vehicleId: Long): Rating?.

The implementation of the method for the sake of simplicity may be:

override fun loadRatingByUserIdAndVehicleId(userId: Long, vehicleId: Long) : Rating? = null

However, when I invoke this method, instead of getting null, I receive the following error message:

2023-06-16 10:40:43,566 ERROR [ExceptionHandler] (executor-thread-1) java.lang.ClassCastException: class kotlin.Unit cannot be cast to class com.example.model.Rating (kotlin.Unit is in unnamed module of loader io.quarkus.bootstrap.classloading.QuarkusClassLoader @470a696f; com.example.model.Rating is in unnamed module of loader io.quarkus.bootstrap.classloading.QuarkusClassLoader @5e5beb8a)
    at com.example.service.RatingService_Subclass.loadRatingByUserIdAndVehicleId(Unknown Source)
    at com.example.service.RatingService_ClientProxy.loadRatingByUserIdAndVehicleId(Unknown Source)

The actual implementation of the method should be:

override fun loadRatingByUserIdAndVehicleId(userId: Long, vehicleId: Long) = 
        ratingRepository.findByUserIdAndVehicleId(userId, vehicleId)
            ?.let { ratingMapper.toBusiness(it, rating, context()) }

And the implementation of findByUserIdAndVehicleId is:

fun findByUserIdAndVehicleId(userId: Long, vehicleId: Long): Rating? {
        return list("userId = ?1 and vehicleId = ?2", userId, vehicleId).firstOrNull()
    }

If the Rating cannot be found by userId and vehicleId, then null is returned. Otherwise, it is converted. Do you have any idea why this error might occur?

EDIT: For demonstration, click here.

  • 1
    Well, *something* is returning `Unit`. You need to figure out what it is. Try using a debugger and stepping through the code line by line. – Jorn Jun 16 '23 at 08:55
  • 1
    I'd also add explicit return types to all functions — just temporarily, to confirm that the expression bodies have the types you expect. – gidds Jun 16 '23 at 08:57
  • 2
    I can't see any obvious issue. But you haven't really given us enough to go on. Can you make a [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) that we can run for ourselves? – gidds Jun 16 '23 at 08:58
  • I have created a playground, that demonstrates the phenomena, click [here](https://github.com/feczkob/kotlin-classcastexception). – Botond Feczkó Jun 16 '23 at 10:27
  • It's unable to start your sample from github. But it have few strange points: – Viacheslav Smityukh Jun 16 '23 at 16:34
  • @ViacheslavSmityukh how did you try to run it? Just use `./gradlew quarkusDev`, or execute the test via `./gradlew quarkusTest`. – Botond Feczkó Jun 16 '23 at 16:48

0 Answers0