haxe icon indicating copy to clipboard operation
haxe copied to clipboard

Null safety: Cannot use "this" until all instance fields are initialized.

Open acarioni opened this issue 3 years ago • 3 comments

Environment macos monterey 12.1 haxe 4.2.4

When null-safety is enabled, it is not possible to get rid of this error even if the offending constructor is annotated with the metadata @:nullSafety(Off). While passing the reference of an object under construction is not generally recommended, there are cases when this isn’t avoidable and is absolutely safe as well.

The error can be reproduced by the following code compiled with the option --macro nullSafety("foo")

package foo;

class Main {
  final a1: A1;
  final a2: A2;

  @:nullSafety(Off)
  public function new() {
    a1 = new A1(this);
    a2 = new A2(this);  
  }
  public static function main() {}
}
class A1 {
  public function new(m: Main) {}
}
class A2 {
  public function new(m: Main) {}
}

The reported error is foo/Main.hx:9: characters 17-21 : Null safety: Cannot use "this" until all instance fields are initialized.

Curiously enough, if the code is modified in the manner below, the compiler stops to complain.

class Main {
  final a1: A1;
  final a2: A2;

  @:nullSafety(Off)
  public function new() {
    a1 = null; a2 = null;
    a1 = new A1(this);
    a2 = new A2(this);  
  }

// ...

acarioni avatar Feb 07 '22 08:02 acarioni

I found that adding the nullSafety annotation before "this" makes disappear the error.

a1 = new A1(@:nullSafety(Off) this)

acarioni avatar Apr 29 '22 06:04 acarioni

I think this still should be fixed for private fields, reopen please

RblSb avatar Apr 29 '22 10:04 RblSb

In general uninitialized private fields still could be accessed through public methods.

back2dos avatar Apr 30 '22 14:04 back2dos