誰かがキーワードを使用する方法/時期/理由を私に説明できますかconst、それとも単に「定数変数を宣言する方法」ですか?もしそうなら、これの違いは何ですか:
int x = 5;
と
const int x = 5;
例を挙げていただけませんか。
誰かがキーワードを使用する方法/時期/理由を私に説明できますかconst、それとも単に「定数変数を宣言する方法」ですか?もしそうなら、これの違いは何ですか:
int x = 5;
と
const int x = 5;
例を挙げていただけませんか。
constコンパイル時定数を意味します。式の値は、コンパイル時に認識されている必要があります。const「値」を変更します。
「const」は、Dartではもう少し複雑で微妙な意味を持っています。constは値を変更します。const [1、2、3]のようにコレクションを作成するとき、およびconst Point(2、3)のように(newではなく)オブジェクトを作成するときに使用できます。ここで、constは、オブジェクトのディープステート全体をコンパイル時に完全に判別でき、オブジェクトがフリーズして完全に不変になることを意味します。
使用する場合
const x = 5次に、変数xは次のようなcosntコレクションで使用できます。
const aConstCollection = const [x];
を使用しない場合はconst、x = 5
const aConstCollection = const [x];違法です。
www.dartlang.orgからのより多くの例
class SomeClass {
static final someConstant = 123;
static final aConstList = const [someConstant]; //NOT allowed
}
class SomeClass {
static const someConstant = 123; // OK
static final startTime = new DateTime.now(); // OK too
static const aConstList = const [someConstant]; // also OK
}
const値に関するいくつかの事実は次のとおりです。
値はコンパイル時に認識されている必要があります。
const x = 5; // OK
実行時に計算されるものはすべてできませんconst。
const x = 5.toDouble(); // Not OK
値は、それが非常に一定であることを意味します。constつまり、そのメンバーのすべてが再帰的に一定であることを意味します。
const x = [5.0, 5.0]; // OK
const x = [5.0, 5.toDouble()]; // Not OK
コンストラクターを作成できますconst。constこれは、クラスから値を作成できることを意味します。
class MyConstClass {
final int x;
const MyConstClass(this.x);
}
const myValue = MyConstClass(5); // OK
const値は正規のインスタンスです。つまり、宣言するインスタンスの数に関係なく、インスタンスは1つだけです。
main() {
const a = MyConstClass(5);
const b = MyConstClass(5);
print(a == b); // true
}
class MyConstClass {
final int x;
const MyConstClass(this.x);
}
であるクラスメンバーがある場合はconst、それもとしてマークする必要がありますstatic。staticクラスに属していることを意味します。値のインスタンスは1つしかconstないため、そうでないことは意味がありませんstatic。
class MyConstClass {
static const x = 5;
}