How constructors can initialize final fields with complex algorithm?

倖福魔咒の 提交于 2020-01-02 20:08:27

问题


I am writing an immutable class Vector3.

class Vector3
{
  final num x, y, z;
  Vector3(this.x, this.y, this.z);
  num get length => ...some heavy code
}

Now, I want to write a constructor that computes the unit vector from another vector. I want to do that according to the Dart's recommendations (avoid writing a static method when we create a new object).

My problem is that I can't write this constructor because the final fields must be initialized before the constructor's body and cannot be initialized inside. I can write something like :

Vector3.unit(Vector3 vector)
  : x = vector.x / vector.length,
    y = vector.y / vector.length,
    z = vector.z / vector.length;

But this is so sad I have to compute three times the length of the vector...

How am I supposed to do that? Should I finally write a static method to compute the unit vector? (It would be a shame)

And, at last, isn't it possible to write anything in the constructor's body related to the initialization of the final fields? And why?

Thanks!


回答1:


Use a factory constructor:

class Vector3
{
  final num x, y, z;
  Vector3(this.x, this.y, this.z);

  factory Vector3.unit(Vector3 vector) {
    var length = vector.length;
    return new Vector3(vector.x/length, vector.y/length, vector.z/length);
  }

  num get length => ...some heavy code
}


来源:https://stackoverflow.com/questions/29134457/how-constructors-can-initialize-final-fields-with-complex-algorithm

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!