override function with concrete type parameter

為{幸葍}努か 提交于 2021-01-28 02:00:28

问题


Hi I would like know why the following example doesn't work

abstract class BaseClass {

}

class ConcretClasOne : BaseCalculator {


}

class ConcretClasTwo : BaseCalculator {


}

abstract class BaseRun {

    abstract fun run(param: BaseClass): Int
}

class ConcretRun : BaseRun {

    override fun run(param: ConcretClasOne): Int {

        return 0
    }
}

this shows me a message run overrides nothing.

I suppose that kotlin isn't able to match the abstract class and the concrete implementation, but what other alternative is there to emulate this behavior, that the run method in the concrete class ConcretRun should receive a concrete param ConcretClasOne?


回答1:


Generics

Using generics, you can make the base class have a type extending the base class, so that the run method can take that type in.

abstract class BaseClass {

}

class ConcretClasOne: BaseCalculator {


}

class ConcretClasTwo: BaseCalculator {


}

abstract class BaseRun<T: BaseClass> {
    abstract fun run(param: T): Int
}

class ConcretRun: BaseRun<ConcretClasOne> {
    override fun run(param: ConcretClasOne): Int {
        return 0
    }
}

Why your code doesn't work

At the moment you are trying to override a method with a more specific type, but as the more general base method can accept more types the more specific method cannot override it.



来源:https://stackoverflow.com/questions/49184239/override-function-with-concrete-type-parameter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!