1

Note : For the sake of simplicity, I removed methods like init and specific functions.

I have an abstract class called Role.

abstract class Role {}

From that class I have inherited many classes like Knight, Sorcerer ... etc.

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

And Then I have created another abstract Class having a generic parameter R : Role

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.

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.

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:

ArrayList<Turn<Role?>>

How can I do it in Kotlin, or is there any other solution? Thank you in advance.

Riadh Adrani
  • 486
  • 2
  • 5
  • 16

2 Answers2

1

For those that didn't see Stachu's response to OP:

The "unsafe" cast operator is used in cases like this.

Code

list.add(knight as Turn<Role>)
Tyluur
  • 95
  • 2
  • 10
1

Declaring your list like this indicates that only Turns with a type parameter of exactly Role can be added to the list.

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

You want to be able to add Turns with anything that derives from Role, if I understand correctly. This means you should use the out keyword:

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

After I make that change, this code compiles without error:

val knight = KnightTurn(Knight())
list.add(knight)
Ben P.
  • 52,661
  • 6
  • 95
  • 123