简体   繁体   English

ArrayList 的 object 的不同(继承)类在 Kotlin 中具有通用参数

[英]ArrayList of object of different (Inherited) classes with a generic parameter in Kotlin

Note: For the sake of simplicity, I removed methods like init and specific functions.注意:为了简单起见,我删除了 init 和特定函数等方法。

I have an abstract class called Role.我有一个名为 Role 的抽象 class。

abstract class Role {}

From that class I have inherited many classes like Knight, Sorcerer... etc.从那个 class 我继承了许多类,如骑士,巫师......等。

class Knight(context: Context) : Role() {}
class Srocerer(context: Context) : Role() {}

And Then I have created another abstract Class having a generic parameter R: Role然后我创建了另一个抽象 Class 具有通用参数R:角色

abstract class Turn<R : Role> {}

Not every role (player) can play a turn不是每个角色(玩家)都能轮到

And as you may expect I also inherited some classes like KngithTurn, SorcererTurn... etc.正如你所料,我还继承了一些类,如 KngithTurn、SorcererTurn... 等。

class KnightTurn(role : Knight) : Turn<Knight>() {}
class SorcererTurn(role : Sorcerer) : Turn<Sorcerer>() {}

The problem is when I create an arrayList of Turn, and try to add an object of type KnightTurn or SorcererTurn, the IDE says that there is a type mismatch despite the fact that they are inherited from class Turn. The problem is when I create an arrayList of Turn, and try to add an object of type KnightTurn or SorcererTurn, the IDE says that there is a type mismatch despite the fact that they are inherited from class Turn.

var list = ArrayList<Turn<Role>>()
val knight = KnightTurn(Knight(baseContext))
list.add(knight) 

// Type mismatch
// Required:Turn<Role>
// Found:KnightTurn

In java, I just solve the problem like this:在 java 中,我只是这样解决问题:

ArrayList<Turn<Role?>>

How can I do it in Kotlin, or is there any other solution?如何在 Kotlin 中做到这一点,或者还有其他解决方案吗? Thank you in advance.先感谢您。

For those that didn't see Stachu's response to OP:对于那些没有看到 Stachu 对 OP 的回应的人:

The "unsafe" cast operator is used in cases like this.在这种情况下使用“不安全”强制转换运算符

Code代码

list.add(knight as Turn<Role>)

Declaring your list like this indicates that only Turn s with a type parameter of exactly Role can be added to the list.像这样声明您的列表表示只有具有完全Role类型参数的Turn可以添加到列表中。

 var list = ArrayList<Turn<Role>>()

You want to be able to add Turn s with anything that derives from Role , if I understand correctly.如果我理解正确,您希望能够将Turn与派生自Role的任何内容一起添加。 This means you should use the out keyword:这意味着您应该使用out关键字:

var list = ArrayList<Turn<out Role>>()

After I make that change, this code compiles without error:在我进行更改后,此代码编译没有错误:

val knight = KnightTurn(Knight())
list.add(knight)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM