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=ხინკალი&oq=ხინკალი&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)
CodePudding user response:
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=ხინკალი&oq=ხინკალი&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.
CodePudding user response:
val newList = sachmelebi.toMutableList().removeAt(asd)
