如何在 Kotlin 中使用 returns 带有类型参数的子类型的方法创建 class?

How to create a class with a method that returns a subtype with a type parameter in Kotlin?

我很难理解泛型/类型参数在 Kotlin 中的工作原理。我正在开发一个(相当复杂的)应用程序,该应用程序在编译期间会抛出一些非常令人困惑的错误消息。我已将以下内容简化为可重现错误的最少代码量。

我有一个接口和两个抽象classes:

interface Player {
    fun play()
}

abstract class Device <T : Player> {
    abstract fun getPlayer(): T
}

abstract class DeviceFactory {
    abstract fun <T : Player> create(): Device<T>
}

当我尝试创建实现 DeviceFactory:

的 class 时出现问题
class MyDeviceFactory : DeviceFactory() {
    
    class MyPlayer : Player {
        override fun play() {
            println("[sound plays here]")
        }
    }
    
    class MyDevice : Device<MyPlayer>() {
        override fun getPlayer() = MyPlayer()
    }
    
    override fun create() = MyDevice()
}

最后一行代码是出现问题的地方,产生了以下错误消息:

Conflicting overloads: public open fun create(): MyDeviceFactory.MyDevice defined in MyDeviceFactory,
public abstract fun  create(): Device defined in DeviceFactory

考虑到问题可能是缺少类型参数,我尝试了这个:

override fun <T : Player> create() = MyDevice()

现在我有不同的错误信息:

Return type of 'create' is not a subtype of the return type of the overridden member
'public abstract fun  create(): Device defined in DeviceFactory'

这没有意义 — MyDeviceDevice<T> 的子类型,对吧?可以肯定的是,我尝试使 return 类型明确:

override fun <T : Player> create(): Device<T> = MyDevice()

没有骰子:

Type mismatch: inferred type is MyDeviceFactory.MyDevice but Device was expected

如何创建一个派生自 DeviceFactory 的 class 和 MyDevice 的一个实例 return?

您需要在 class:

上声明 DeviceFactory 的类型
abstract class DeviceFactory<T : Player> {
    abstract fun create(): Device<T>
}

然后你可以定义一个工厂returns一个具体的Player:

class MyDeviceFactory : DeviceFactory<MyPlayer>() {
    override fun create(): Device<MyPlayer> = MyDevice()
}