0

Trying to create a clone of ArrayList players. I want to clone it entirely (the ArrayList including its contents).

Activity.kt

lateinit var playersinfo: PlayersInfo
lateinit var players: ArrayList<Player>
lateinit var tempPlayers: ArrayList<Player>

override fun onCreate(savedInstanceState: Bundle?) {

val intent = intent
playersinfo = intent.getParcelableExtra<PlayersInfo>("playersinfo")
players = playersinfo.players
var tempPlayers: ArrayList<Player> = players.clone() // RETURNS ERROR
players.forEach { tempPlayers.add(it)}

tempPlayers initialisation returns this error: enter image description here

Player.kt

@Parcelize
data class Player (
    val name: String,
    val age: Int,
    val gender: String
): Parcelable

@Parcelize
class PlayersInfo(
    val players: ArrayList<@RawValue Player>, val anyBelow18: Boolean = players.any { player -> player.age < 18 },
    var location: String = "Other"
): Parcelable {

}

Any idea what the problem is?

Zorgan
  • 8,227
  • 23
  • 106
  • 207
  • I actually don't understand what the confusion is. `#clone()` returns `Any`, not `ArrayList` so you obviously need to cast. – Tom Apr 06 '19 at 05:48
  • So what's the point of cloning if you have to create the cloned array by doing `players.forEach { tempPlayers.add(it)}` anyway? – Zorgan Apr 06 '19 at 05:49
  • In Java you would write `List tempPlayers = new ArrayList<>(players);`. The `clone()` method is not particularly useful for generic collections because casting to a generic type gives a compiler error. – Stephen C Apr 06 '19 at 06:15
  • "So what's the point of cloning if you have to create the cloned array by doing players.forEach { tempPlayers.add(it)} anyway?" Don't blame Kotlin when you do unnecessary stuff. I don't know why you've added it, but you don't need that. – Tom Apr 06 '19 at 06:23
  • @StephenC The Kotlin equivalent would be `tempPlayers = ArrayList(players)` (I removed `var` and `type`, because that would shadow an existing property (that is why `var` is highlighted in OPs code)) – Tom Apr 06 '19 at 06:28
  • Thanks @Tom `tempPlayers = ArrayList(players)` is what I was seeking. When would `clone()` be useful? – Zorgan Apr 06 '19 at 06:51

0 Answers0