Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Out-projected type 'ArrayList<*>' prohibits the use of 'public open fun add(index: Int, element: E): Unit defined in java.util.ArrayList'

Tags:

I have this snippets:

class RecyclerViewAdapter internal constructor(     val clazz: Class<out RecyclerViewViewHolder>,     val layout: Int,     var dataList: MutableList<*>) ... ... ... fun RecyclerView.getDataList() : ArrayList<*> {   return (adapter as RecyclerViewAdapter).dataList as ArrayList<*> } ... ... ... 

then I use that on this:

recyclerView.getDataList().add(Person("Lem Adane", "41 years old", 0)) 

but I get this error:

Error:(19, 31) Out-projected type 'ArrayList<*>' prohibits the use of    'public open fun add(index: Int, element: E): Unit defined in   java.util.ArrayList' 
like image 448
LEMUEL ADANE Avatar asked Nov 10 '16 04:11

LEMUEL ADANE


1 Answers

Kotlin star-projections are not equivalent to Java's raw types. The star (*) in MutableList<*> means that you can safely read values from the list but you cannot safely write values to it because the values in the list are each of some unknown type (e.g. Person, String, Number?, or possibly Any?). It is the same as MutableList<out Any?>.

In contrast, MutableList<Any?> means that you can read and write any value from and to the list. The values can be the same types (e.g. Person) or of mixed types (e.g. Person and String).

In your case you might want to use dataList: MutableList<Any> which means that you can read and write any non-null value from and to the list.

like image 62
mfulton26 Avatar answered Sep 28 '22 03:09

mfulton26