Kotlin: java.lang.UnsupportedOperationException in MutableList add element

前端 未结 2 1896
伪装坚强ぢ
伪装坚强ぢ 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<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]
    }
    
    0 讨论(0)
  • 2021-01-19 02:13

    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.

    0 讨论(0)
提交回复
热议问题