Member initialization bypasses setter

The following code reports just one assignment, although two are done.

class A() {
    var x: Int = 1
        set(value) {
            println("Setting value $value")
            field = value
        }
}
val a = A()
a.x = 2

Is this the intended behaviour? And if so why?

Yeah this is intended behaviour (even tho it is a bit confusing).

When you write:

var x: Int = 1

You are not calling setter, you are assigning value directly into field.

1 Like

This is even more confusing, if you consider, that the init { } block uses the setter.

Yes, you can have something like this, and setter will be called.

class A {
    var x: Int
        set(value) {
            println("Setting value $value")
            field = value
         }

   constructor(){
      x = 1
   }
}

Just be careful accessing field in setter because it can lead to NPE if value is not initialised.

The IDE suggests that I should not care about.
https://issuetracker.google.com/issues/261329821

I think that compiler is looking at the property type, and since it is not nullable suggest that checking if it’s null doesn’t make sense.