Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call ArrayAdapter.addAll method in Kotlin?

Tags:

I have a very simple list (so it isn't necessary to create a custom adapter which extends BaseAdapter). I use an ArrayApdater to implements this.

When I want to change the value of the adapter, there's a build error says there's two allAll methods and kotlin don't know which one to use.

Here's the sample code:

    val list = Collections.emptyList<Any>() // Just for sample.
    val adapter = ArrayAdapter<Any>(this, android.R.layout.simple_spinner_item, list) // This line is OK
    // Some work later
    adapter.clear()
    adapter.addAll(list) // Here's the error

The error message is :

    Error:(79, 35) Overload resolution ambiguity:
    public open fun addAll(p0: (MutableCollection<out Any!>..Collection<Any!>?)): Unit defined in android.widget.ArrayAdapter
    public open fun addAll(vararg p0: Any!): Unit defined in android.widget.ArrayAdapter

How to solve it?

like image 871
6v_ Avatar asked Aug 14 '17 10:08

6v_


2 Answers

There are two addAll methods in ArrayAdapter:

  1. ArrayAdapter.addAll(T ... items)
  2. public void addAll(@NonNull Collection<? extends T> collection).

so compiler is unable to infer which one method you want to call, because Any is somewhat like Object in Java.

Instead of : val list = Collections.emptyList<Any>() use val list = Collections.emptyList<String>().

And change ArrayAdapter<Any> to ArrayAdapter<String>

Error should be resolved.

Hope it helps.

like image 102
chandil03 Avatar answered Oct 11 '22 12:10

chandil03


You should use String instead of Any

Your code should be like this.

val list = Collections.emptyList<String>() // Just for sample.
        val adapter = ArrayAdapter<String>(activity, R.layout.simple_spinner_item, list) // This line is OK
        // Some work later
        adapter.clear()
        adapter.addAll()
like image 20
Bhuvanesh BS Avatar answered Oct 11 '22 14:10

Bhuvanesh BS