Blog

[dart] const, final

Published 1 min read

Similarity
Both make a constant.

Difference
They're initialized at different times.

Initialization time
const → value is decided at compile time → value can't be decided at runtime
final → value can be decided even after compile time → value can be decided at runtime too

(+ A List defined with final can still use add operations.)

Example
There's a function called DateTime.now().
This function gets the current time, so the value is different every time you call it.
That means you have to actually run the program to see the value the function returns. (= you can see it at runtime)

The const keyword can't decide a value at runtime,
and the final keyword can decide a value at runtime, so you get the following result.
(If the function's constructor is defined as const, it won't error with const either)

final DateTime curTime = DateTime.now(); // no problem const DateTime curTime = DateTime.now(); // compile error

Comments

Leaving a comment stores your nickname (or GitHub profile info). Privacy policy

GitHub