Kotlin: java.lang.UnsupportedOperationException in MutableList add element

前端 未结 2 1902
伪装坚强ぢ
伪装坚强ぢ 2021-01-19 01:31

I\'m implementing a stack algorithm for study purpose in Kotlin

class Stack>(list:MutableList) {

    var items: Mutabl         


        
2条回答
  •  终归单人心
    2021-01-19 02:12

    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 = listOf("foo", "bar", "baz")
        //val y: MutableList = x as MutableList throws UnsupportedOperationException
        val y: MutableList = x.toMutableList()
        y.add("sha")
        println(y) // [foo, bar, baz, sha]
    }
    

提交回复
热议问题