Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with function Overloading in kotlin

I am trying to declare two suspend methods with list of String and PublishRequest Object as parameter. But the IDE is giving error with this. The error is either make one of the function internal or remove suspend. But i want to use coroutines inside both of them.

    override suspend fun publish(publishRequests: List<PublishRequest>) {
       ///code

    }


    suspend fun publish(events: List<String>) {
     ///code

    }

The PublishRequest Data class is internal. The issues is only coming when we add the publish(events: List) method. The code is working fine the publish(publishRequests: List)

Can you explain why it is happening ?

like image 678
Naman_Jain Avatar asked Sep 04 '25 17:09

Naman_Jain


1 Answers

The problem you are facing is related to type erasure.

The types List<PublishRequest> and List<String> are erased to List<*>, as consequence, you would have a JVM signature clash.

To solve your problem you have two different solutions.

  1. Change their names and avoid a signature clash:
    suspend fun publishRequests(publishRequests: List<PublishRequest>) {}
    suspend fun publishEvents(events: List<String>) {}
  1. Use a single function with a reified type and handle the different type classes inside that function:
suspend inline fun <reified T> publish(objects: List<T>) {
    when {
        PublishRequest::class.java.isAssignableFrom(T::class.java) -> // it's a list of PublishRequest
        T::class == String::class -> // it's a list of String
    }       
}
like image 107
Giorgio Antonioli Avatar answered Sep 07 '25 17:09

Giorgio Antonioli