Reputation: 93
I am trying to use apply function for assign a new value to a variable. when i try apply() to re-assign a value to a parameter of a data class it works correctly. but when i have not a data class it does not work!
data class example:
data class A(
var a: Int,
)
val a1 = A(3)
val a2 = a1.apply {
a = 5
}
println("a1 = ${a1.a}, a2 = ${a2.a}")
basic type example:
var a1 = 3
var a2 = a1.apply {
a1 = 5
}
println("a1 = $a1, a2 = $a2")
the result of first example is:
a1 = 5, a2 = 5
but the result of second example is:
a1 = 5, a2 = 3
I don't understand why a2
still is 3 and apply does not work for it!
I expected the a1 = 5
re-assign 5 value to a2
but it does not!
Can you explain it?
Upvotes: 1
Views: 286
Reputation: 93739
The Int class is immutable. You cannot change the value of an instance of it. Note the difference in your two code samples. In the first, you are changing the a
property of your A
class to have a different value. So, you are mutating the instance of A
.
In your second code sample, you are not changing a value that is inside the instance. You are changing your variable a1
to point to a completely different instance of Int. Your apply
block is pointless, because you aren't using it to call any member functions or properties of the Int class. You are directly reassigning the variable a1
.
All the Kotlin standard library Number classes, as well as String, BigInteger, and BigDecimal, are immutable classes, where you cannot change the value inside the instance. You can only reassign variables/properties to point to other instances.
Upvotes: 1