如何在构造函数中初始化final类属性? [英] How do I initialize a final class property in a constructor?

查看:171
本文介绍了如何在构造函数中初始化final类属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,您可以执行以下操作:

In Java you are allowed to do this:

class A {    
    private final int x;

    public A() {
        x = 5;
    }
}

在Dart中,我尝试过:

In Dart, I tried:

class A {    
    final int x;

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

我遇到两个编译错误:


必须初始化最终变量'x'。

The final variable 'x' must be initialized.


'x'不能用作设置器,因为它是最终的。

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

是否可以在Dart中的构造函数中设置最终属性?

Is there a way to set final properties in the constructor in Dart?

推荐答案

无法实例化构造函数主体中的final字段。

You cannot instantiate final fields in the constructor body. There is a special syntax for that:

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));
}

这篇关于如何在构造函数中初始化final类属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆