Max Yankov
Max Yankov

Reputation: 13297

How do I initialize a final field in constructor's body?

Basically, that's what I'm trying to do:

  ClassName
  {
    final OtherClass field;

    ClassName()
    {
      field = new OtherClass(this);
    }
  }

Upvotes: 45

Views: 28381

Answers (3)

CopsOnRoad
CopsOnRoad

Reputation: 267454

With null safety, you can initialize a final field in different ways:

  • At declaration:

    class Foo{
      final int bar = 1;
    }
    
  • In constructor parameter (initializing formal).

    class Foo {
      final int bar;
    
      // Initializing in constructor parameter.
      Foo(this.bar);
    }
    
  • In the initializer list.

    class Foo {
      final int bar;
    
      // Initializer list
      Foo() : bar = 1;
    }    
    
  • Combination of above two.

    class Foo {
      final int bar;
    
      Foo(int value) : bar = value;
    }
    
  • Use late keyword for lazy initialization.

    class Foo {
      late final int bar; // Initialize it later, maybe in a method
    }
    

Upvotes: 25

Alexander Kremenchuk
Alexander Kremenchuk

Reputation: 396

Since Dart 2.12 it is possible by using late keyword. The code below prints 5:

class ClassName
  {
    final int var1 = 5;
    late final OtherClass field;

    ClassName()
    {
      field = new OtherClass(this);
    }
  }

class OtherClass {
  OtherClass(ClassName object) {
    print(object.var1);
  }
}

void main() {
  final object = ClassName();
}

Please see this and the following sections

Upvotes: 3

Fox32
Fox32

Reputation: 13560

It's not possible to assign a final field in a constructor body. The final field needs to be assigned before the constructor body, in the initializer list or on declaration:

class ClassName
{
    final OtherClass field = new OtherClass(); // Here

    ClassName()
        : field = new OtherClass() // or here 
    {
     
    }
}

As you can't use this in the initializer list or on the declaration, you can't do what you plan to do.

Upvotes: 53

Related Questions