I\'m implementing a stack algorithm for study purpose in Kotlin
class Stack>(list:MutableList) {
var items: Mutabl
You can fix this by calling toMutableList() api rather than using smart cast (as).
Try: var initialValue = listOf< Int >(10).toMutableList()
Below is a working example:
fun main(){
val x : List<String> = listOf("foo", "bar", "baz")
//val y: MutableList<String> = x as MutableList<String> throws UnsupportedOperationException
val y: MutableList<String> = x.toMutableList()
y.add("sha")
println(y) // [foo, bar, baz, sha]
}
listOf<Int>
is not truly mutable. According to the doc:
fun <T> listOf(vararg elements: T): List<T> (source)
Returns a new read-only list of given elements. The returned list is serializable (JVM).
You should use mutableListOf<> instead.
The reason why as MutableList
is permitted here is because listOf(10)
returns Collections.singletonList(10)
which returns a java.util.List
(which Kotlin assumes implements the kotlin.collections.MutableList
interface). So the compiler does not know it's not really mutable until the mutating method is called at runtime and throws the exception.