I'm doing the code migration from java to kotlin and I have some problem with generics.
This is an example explaining my doubts:
import java.util.*
import kotlin.collections.HashMap
interface MyGenerics<T>{
fun produce():T
fun publish(toPublish:T):String
}
class MyImplementation:MyGenerics<Boolean>{
override fun produce(): Boolean {
return true
}
override fun publish(toPublish: Boolean): String {
return "test"
}
}
class RegistrationClass{
private val workers = HashMap<String, Vector<MyGenerics<Any>>>()
fun register(type: String, worker: MyGenerics<Any>) {
if (!workers.containsKey(type)) workers[type] = Vector()
workers[type]!!.add(worker)
//usage example
for (workers in workers[type]!!){
val product = workers.produce()
workers.publish(product)
}
}
}
fun main() {
val registrationClass = RegistrationClass()
registrationClass.register("MyTest", MyImplementation()) //error kotlin implementation
val javaRegistrationClass = JavaRegistrationClass()
javaRegistrationClass.register("MyNewTest", MyImplementation()) //java implementation
}
Why I'm getting error on
> registrationClass.register("MyTest", MyImplementation()) //error
> kotlin implementation
and not on:
javaRegistrationClass.register("MyNewTest", MyImplementation()) //java implementation
This is the JavaRestristrationClass:
class JavaRegistrationClass{
private HashMap workers = new HashMap<String, Vector<MyOtherTest>>();
public void register(String type, MyGenerics worker) {
//do something
}
}
I have read this https://stackoverflow.com/a/65534086/3681634 answer, but I continue to not understand