Dart assigning to variable right away or in constructor?

前端 未结 1 676
离开以前
离开以前 2020-12-20 06:01

In Dart, is there a difference in assigning values right away vs in constructor like in Java?

class Example {
    int x = 3;
}

vs



        
1条回答
  •  青春惊慌失措
    2020-12-20 07:00

    In your trivial case, it doesn't matter.

    In general, you can initialize instance variables in a few ways:

    Inline

    class Example1 {
      T x = value;
    }
    

    Advantages:

    • Direct, concise.
    • Member will be initialized in all constructors.
    • Can be used to initialize final members.
    • Member is initialized before invoking base class constructors, which can matter if the base class constructor calls member functions that are overridden by the derived class.

    Disadvantages:

    • Can't depend on construction arguments.
    • Can't depend on this since the initialization occurs before this becomes valid.

    Initialization list

    class Example2 {
      T x;
    
      Example2() : x = value;
    }
    

    Advantages:

    • Can be used to initialize final members.
    • Member is initialized before invoking base class constructors, which can matter if the base class constructor calls member functions that are overridden by the derived class.
    • Can utilize construction arguments.

    Disadvantages:

    • If the class has multiple constructors, initialization would need to be duplicated, or constructors should redirect to a common constructor.
    • Can't depend on this since the initialization occurs before this becomes valid.

    Constructor body

    class Example3 {
      T x;
    
      Example3() {
        x = value;
      } 
    }
    

    Advantages:

    • Can utilize construction arguments.
    • Can be used to perform more complicated initialization, such as cases where the member cannot be initialized via a single expression.
    • Can use this.

    Disadvantages:

    • Cannot be used to initialize final members.
    • If the class has multiple constructors, initialization would need to be duplicated or initialization code would need to be refactored out (such as, but not limited to, redirecting to a common constructor).
    • Member is initialized after invoking base class constructors.

    There probably are some points I'm forgetting, but I think that should cover the main ones.

    Direct, inline initialization occurs first, then initialization lists, then constructor bodies. Also see Difference between assigning the values in parameter list and initialiser list which explains why this becomes valid only for the later stages of object initialization.

    0 讨论(0)
提交回复
热议问题