Frank Lin
Frank Lin

Reputation: 25

Kotlin in the forEach, why it can be reassigned if it is an array?

I found out a weird situation when I was solving the problem in Leetcode. Normal

var a = listOf(1,2,3)
a.forEach{it++}

Obviously, compiler shows it can not be reassigned. However!! Why it works in the below situation?

//An 2 by 2 matrix :[[0,0],[0,0]]
val matrix = Array(2,init = {IntArray(2,init = {0})})
matrix.forEach {it[0]++}
//get a new matrix : [[1,0],[0,0]]

matrix has been reassigned right?
Can someone tell me about what is going on?

Upvotes: 2

Views: 494

Answers (2)

Ilya
Ilya

Reputation: 23125

matrix val isn't reassigned here, and moreover it can't be reassigned because it's declared as val. You can verify it pretty easily:

val matrix = Array(2,init = {IntArray(2,init = {0})})
val originalMatrix = matrix
matrix.forEach {it[0]++}

println(matrix === originalMatrix) // prints true

But what happens instead?

matrix is an object here or, more specifically, an array, whose elements are arrays as well. In the expression matrix.forEach { it ... }, it is a matrix element, and its type is IntArray. Finally, it[0]++ is the same as it[0] = it[0] + 1, so for IntArray it's a perfectly valid operation that increments its first Int element's value.

Upvotes: 1

Tenfour04
Tenfour04

Reputation: 93649

Writing it[0]++ is syntactic sugar for writing it.set(0, it.get(0) + 1). You're not trying to assign a value to the read-only value it. You are calling a function on an object.

Upvotes: 5

Related Questions