Home > Blockchain >  Mutability in kotlin object
Mutability in kotlin object

Time:10-13

I'm studying mutability special cases in Kotlin.

this is the code I was playing with:

var a = 350
val b = a
a = 8
println(b) // 350. ===> should be 8

I want to keep the b as val but at the same time it should be able to take the value of a each time a variable is modified.

So I tried the object solution but as you see below, the x variable is not accessible. I suppose this solution is not correct.

val object1 = object {
    var x = 350
}
val object2 = object1
object1.x = 8
println(object2.x)

Is there a way to synchronize this x but without putting the block in a synchronized annotated funchtion like below ?

@Synchronized
fun someFunction(): Int {

    val object1 = object {
        var x = 350
    }
    val object2 = object1
    object1.x = 8
    println(object2.x)

return object2.x
}
someFunction()

CodePudding user response:

You can just define b as a property that references a:

var a=350
val b: Int
    get()=a

Everytime you access b, it will redirect that access to a.

The following will print 8 and you don't have to use your object solution:

var a=350
val b: Int
    get()=a
fun main() {
    a=8
    println(b)
}
  • Related