https://kotlinlang.org logo
#getting-started
Title
# getting-started
s

Simon Lin

01/05/2022, 6:58 AM
How can I add element in specified index and if the index exist element, replace it.
Copy code
val list = mutableListOf<String>()

list.add(0, "a")
list.add(0, "b")

list.toString() // except [b], actual [b, a]
g

gildor

01/05/2022, 7:04 AM
use list[0] = “b”
it’s the same as list.set(0, “b”)
s

Simon Lin

01/05/2022, 7:06 AM
How about the
a
? If call list[0] = “a” will cause exception
Is there a convenient way for each insert without check the list
g

gildor

01/05/2022, 7:10 AM
What is your use case? I’m just not quite sure what if you real life example for this
If you just need a function which does ” add element in specified index and if the index exist element, replace it.“, there is no such function in stdlib, it’s probably better just to create own extension for this
🙆‍♂️ 1
Still curious about your use case for this
s

Simon Lin

01/05/2022, 7:18 AM
I need to show the list data according to its index and the user can add data into the list. first, the list is empty. User can only inset to 0 index then, user can choose to insert data to the end or selected the data that insert early and replace its value.
g

gildor

01/05/2022, 7:21 AM
But insert is not replace
or selected the data that insert early and replace its value.
I think no need to overthink this, it’s just easy to check if there is item and set it
s

Simon Lin

01/05/2022, 7:23 AM
ok ty 😀
I was affect by the SQL
The INSERT OR REPLACE Statement.
g

gildor

01/05/2022, 7:57 AM
Problem that there is no built-in transaction on list unlike database, checking for “contains” is a separate operation from add/set, so it cannot be done in a safe way under the hood of the list, only for thread safe list implementations, which are not used by default, because of performance penalty
🙆‍♂️ 1
6 Views