Home > OS >  Kotlin - Override a function with Generic return type
Kotlin - Override a function with Generic return type

Time:10-29

I have an interface. I want to make the return type of one of the function in that interface as generic type. Depend on how it is going to override, the return type will determine. When I try below code, I get errors Conflicting overloads: . I am new to Kotlin.

interface Loader<T> {

     fun <T> doSomething(inputParams: Map<String, String> = emptyMap()): T?

     fun cancelSomething(inputParams: Map<String, String> = emptyMap())
}

class LoaderHandler<MutableMap<String, String>> (private val foo: Foo) : Loader<MutableMap<String, String>> {

    override fun doSomething(inputParams: Map<String, String>): MutableMap<String, String>? { 
        // some code goes here.
        return mapOf("x" to "y")
    }

    override fun cancelSomething (inputParams: Map<String, String>) {
        println("cancelSomething")
    }

How can I implement the doSomething(...) function with return type of Map.

CodePudding user response:

Delete <T> in

 fun <T> doSomething(inputParams: Map<String, String> = emptyMap()): T?

It is not doing what you think it is.

Additionally,

class LoaderHandler<MutableMap<String, String>> (private val foo: Foo) : Loader<MutableMap<String, String>> {

should be

class LoaderHandler(private val foo: Foo) : Loader<MutableMap<String, String>> {
  • Related