具有具体类型参数的替代功能 [英] override function with concrete type parameter

查看:71
本文介绍了具有具体类型参数的替代功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么下面的示例不起作用

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
    }
}

这向我显示一条消息run overrides nothing.

我认为kotlin无法匹配抽象类和具体实现,但是还有什么其他替代方法可以模拟这种行为,具体类ConcretRun中的run方法应该接收具体参数?

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?

推荐答案

泛型

使用泛型,可以使基类具有扩展基类的类型,以便run方法可以采用该类型.

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.

这篇关于具有具体类型参数的替代功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆