What is the difference between constructor and initializer list in Dart?

后端 未结 1 724
野的像风
野的像风 2021-02-09 09:03

Problem

The output of the following two codes are the same, but what is the essential difference?

A Tour of the Dart Language - Initializer list



        
相关标签:
1条回答
  • 2021-02-09 09:38

    There is no difference, the result will be the same except that you can take advantage of different type of constructors.

    In the case you don't want to expose your variables defined in Point and your mark those as private, the initializer would be a good option.

        class Point {
          final num _x;
          final num _y;
          final num _distanceFromOrigin;
    
          Point(x, y)
              : _x = x,
                _y = y,
                _distanceFromOrigin = sqrt(x * x + y * y);
        }
    

    Also take a look to the constructor with optional parameters or factory constructors.

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