I recently started developing android apps in kotlin and have across this issue. I have var employees Arraylist declared and assigned null at the start of my activity, which I later add string values to in my OnCreate method.
var employees: ArrayList<String>?= null
Now,when I add values to it I get an Assignment operators ambiguity error.
Upon doing some research on the internet I found that += operation with a mutable list has two possible interpretations - either to append an item to the existing list or to create a new list by appending the new value to the old list and to store the reference to the new list in the variable. from here
Now my question is how do I make the compiler choose from one of the interpretations to add to my mutable list.
Thank You.
You can just choose one by yourself, depending on your requirement.
If you just want to add an employee into the employees
:
var employees: ArrayList<String>? = null
employees?.plusAssign("employee")
If you want the employees
be assigned to a new List
which contains the added employee:
var employees: List<String>? = null
employees = employees?.plus("employee")
Note the difference between the declarations. But I think it's better to add an employee just using the add()
function of ArrayList
:
var employees: ArrayList<String>? = null
employees?.add("employee")
I think there is no need to stick to the assignment operator after all, it's just a convenient way to the method calls :)