Kotlin: java.lang.UnsupportedOperationException in MutableList add element

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

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

class Stack>(list:MutableList) {

    var items: Mutabl         


        
2条回答
  •  猫巷女王i
    2021-01-19 02:13

    listOf is not truly mutable. According to the doc:

    fun listOf(vararg elements: T): List (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.

提交回复
热议问题