removeAt not functioning in kotlin
I've a list of objects, I want to remove the element with its index, here's my code but it doesn't work, returns an error saying:unresolved reference: removeAt println(sachmelebi.removeAt(asd))
fun main() {
data class SachmelebiClass(
val name: String,
val link: String
)
val sachmelebi = listOf(
SachmelebiClass(
"ხინკალი",
"https://www.google.com/search?q=%E1%83%AE%E1%83%98%E1%83%9C%E1%83%99%E1%83%90%E1%83%9A%E1%83%98&oq=%E1%83%AE%E1%83%98%E1%83%9C%E1%83%99%E1%83%90%E1%83%9A%E1%83%98&aqs=chrome..69i57j46j0l6.1143j0j9&sourceid=chrome&ie=UTF-8"
),
SachmelebiClass(
"aa",
"aaa"
),
SachmelebiClass(
"bb",
"bbb"
)
)
val randomColor = sachmelebi.random()
println()
val asd = sachmelebi.indexOf(randomColor)
sachmelebi.removeAt(asd)
listOf()
returns a read-only view of the underlying List
so you need a mutable List as follows:
val sachmelebi = mutableListOf(
SachmelebiClass(
"ხინკალი",
"https://www.google.com/search?q=%E1%83%AE%E1%83%98%E1%83%9C%E1%83%99%E1%83%90%E1%83%9A%E1%83%98&oq=%E1%83%AE%E1%83%98%E1%83%9C%E1%83%99%E1%83%90%E1%83%9A%E1%83%98&aqs=chrome..69i57j46j0l6.1143j0j9&sourceid=chrome&ie=UTF-8"
),
SachmelebiClass(
"aa",
"aaa"
),
SachmelebiClass(
"bb",
"bbb"
)
)
(As discussed in the comments with @Tenfour04, the striked-through suggestion has so many disadvantages that it is better to not even mention it. Thanks @Tenfour04 for the hints.)
Another possibility, most probably a better one, is to stick with read-only Lists and do the following instead:
val finalSachmelebi = sachmelebi.minus(randomColor)
This will create a new List with the final result. Mutable lists is usually a source of bugs, and that is why using read-only lists is usually preferable.