How to Resolve "java.util.Collections$SingletonList cannot be cast to java.util.ArrayList" Issue in Kotlin?

37 views Asked by At

I encountered an issue while trying to convert a list using the distinct() method in Kotlin. Here's a simplified version of my code:

        val orgList = arrayListOf<ListArticle>()
        orgList.add(list)
        val sortedList = orgList.distinct() as ArrayList<ListArticle>
1

There are 1 answers

0
Ashwin Nirmale On

Absolutely! We can resolve this issue by simply wrapping the distinct list in an ArrayList() constructor. Here's how:

 val list: ArrayList<ListArticle> = ArrayList(orgList.distinct())

This converts the distinct list into an ArrayList, ensuring compatibility and avoiding any ClassCastException issues. Smooth sailing ahead!