F
F
foonfyrick2020-11-03 12:11:03
Kotlin
foonfyrick, 2020-11-03 12:11:03

Why doesn't the setter fire when assigning a constructor argument?

Why if the constructor argument is assigned to a property, then the setter does not work, but if it is removed and property a is initialized, then the setter works?

class Test(b:Int) {
    var a:Int = b
        set(value) {
            if (value>0) field=1
            else field=-1
        }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2020-11-03
@foonfyrick

The answer is because the Kotlin compiler (more precisely, its creators) thinks that this is correct. It compiles to bytecode, which is similar to this Java code:

public final class Test {
   private int a;

   public final int getA() {
      return this.a;
   }

   public final void setA(int value) {
      if (value > 0) {
         this.a = 1;
      } else {
         this.a = -1;
      }

   }

   public Test(int b) {
      this.a = b;
   }
}

Why so - you can guess, here are the possible reasons:
* you can refer to a field that has not yet been initialized
* you can refer to other fields that are in the source code below, and therefore will be initialized later.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question