Search code examples
arrayskotlingetter-setter

"No set method providing array access" -- why does this happen in Kotlin?


Here's the code.

val stack = Array(inputString.length + 1) { "" }
var current = 0
for ((i, char) in inputString.withIndex()) {
    if (char == '(') {
        current += 1
        continue
    } else if (char == ')') {
        val enclosedString = stack[current]
        stack[current - 1] = stack[current - 1] + enclosedString.reversed()
        current -= 1
        continue
    } else {
        stack[current] +=  char //here's the compile time error 
    }
}

I'm getting an error saying "No set method providing array access". I don't understand this.

If I change it to:

stack[current] = stack[current] + char

things work fine.

Why is this happening?


Solution

  • The cause of the error is the incorrect assignment of a Char variable to an Array<String>, you need to convert the Char to String before, and that's what is happening in the statement

    stack[current] = stack[current] + char
    

    The + function returns a new String concatenating with the string representation of the right side (i.e. it automatically call toString in the right operand). In other words, it is converting the Char variable char to String before the concatenation.

    You can also convert it yourself.

    stack[current] += char.toString()