constructor - 如何在构造函数中初始化最终类属性?

标签 constructor dart final

在 Java 中你可以这样做:

class A {    
    private final int x;

    public A() {
        x = 5;
    }
}

在 Dart 中,我尝试过:

class A {    
    final int x;

    A() {
        this.x = 5;
    }
}

我收到两个编译错误:

The final variable 'x' must be initialized.

'x' can't be used as a setter because its final.

有没有办法在 Dart 的构造函数中设置最终属性?

最佳答案

无法在构造函数主体中实例化最终字段。有一个特殊的语法:

class Point {
  final num x;
  final num y;
  final num distanceFromOrigin;

  // Old syntax
  // Point(x, y) :
  //   x = x,
  //   y = y,
  //   distanceFromOrigin = sqrt(pow(x, 2) + pow(y, 2));

  // New syntax
  Point(this.x, this.y) :
    distanceFromOrigin = sqrt(pow(x, 2) + pow(y, 2));
}

关于constructor - 如何在构造函数中初始化最终类属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42864913/

相关文章:

Java:Spring Boot 类构造函数有太多 DI?

dart - 约束.hasBoundedHeight' : is not true flutter

dart - "The argument type ' 字符串? ' can' t 分配给参数类型 'String' "使用 stdin.readLineSync() 时

php - 在 php 和 dart 之间发送数据

Java final 字段编译时常量表达式

java - Java中的静态字符串路径

c++ - 这个拷贝构造函数做的是深拷贝还是浅拷贝?

c++ - 当我们进行复制初始化时,复制构造函数或构造函数是否起作用

javascript - 构造函数和原型(prototype)

java - 私有(private)最终 HashSet 如何工作?