Reputation: 11
This gives Exception in thread "main":
java.lang.UnsupportedOperationException: remove
fun main(args: Array<String>) {
val list = listOf(0, 1, 2, 3, 4, 5, 6, 7, 8);
var record: MutableList<Int>;
record = list as MutableList<Int>;
record.remove(2);
print(record);
}
Upvotes: 0
Views: 753
Reputation: 93609
Casting does not change an object into a different kind of object. When you assign list
to record
, it is still a read-only List
, but you've forced the compiler to treat it like a MutableList
, so it will fail at runtime instead of compile time.
Since you instantiate list
as a read-only List
, it is protected from changes (at least to its size). If that is not what you want, you should instantiate it as a MutableList
to begin with. Or if you just need a copy of it that you can change, you can use toMutableList()
to get a copy.
Upvotes: 3
Reputation: 18002
You should use .toMutableList() to copy the list in a new mutable list:
val list = listOf(0, 1, 2, 3, 4, 5, 6, 7, 8)
val record = list.toMutableList()
record.remove(2)
print(record)
This outputs:
[0, 1, 3, 4, 5, 6, 7, 8]
Upvotes: 1