Gus W
Gus W

Reputation: 128

Casting Kotlin ArrayLists ClassCastException

I have a MutableList<Card> called cards that I am sorting based on one of the properties, using the sortedWith function. This returns a sorted generic list type, so a cast is necessary. However, when I cast the list, it crashes with a ClassCastException:

private var cards: MutableList<Card> = ArrayList()
...
cards = cards.sortedWith(compareBy{it.face}) as ArrayList<Card>



java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList

EDIT: I just realized I need to use the more generic type of cards for the cast, MutableList<Card>. Now, can someone explain why the cast with ArrayList fails?

Upvotes: 2

Views: 1898

Answers (2)

user8959091
user8959091

Reputation:

There are easier ways to sort a list in place without creating a new one and assign back to the original. The simplest is cards.sortBy { it.face }

Upvotes: 0

Ilya
Ilya

Reputation: 23174

The cast fails because the list returned by sortedWith function is not an instance of java.util.ArrayList.

Moreover it's unsafe to cast it to MutableList too, because the implementation of sortedWith can be changed later, so that it returns List that's no longer a MutableList.

If you have a MutableList and you want to sort it, you have two options:

  • either sort it in-place with the sortWith function (not sortedWith):

    cards.sortWith(compareBy{it.face})
    // now cards list is sorted
    
  • or sort it to a new list and then copy it to a mutable list, if you need to mutate it after

    cards = cards.sortedWith(compareBy{it.face}).toMutableList()
    

Upvotes: 5

Related Questions