Hemel
Hemel

Reputation: 313

How constructors can initialize final fields with complex algorithm?

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!

Upvotes: 3

Views: 588

Answers (1)

Ozan
Ozan

Reputation: 4415

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
}

Upvotes: 7

Related Questions