Final keyword in Dart
In Darts“final” means single-assignment, Once assigned with value then variable value can’t be changed. Final key word makes variable to hold constant value at compile time and runt time as well.
final int age = 25; final var date = DateTime.now() // Final keyword accepts runt time data as well
Class Level Final Variables: The below example illustrates final keyword behaviour:
Class Product {
final String productName;
final int productId;
Product(this.productName,this.productId);
}
void main() {
Product pr= new Product("Laptop",101);
}
Class Level Static Variables:
Class Level static variables must be initialized at same time, does not allow at constructor level.
Class Product { final static productName = "Laptop"; }
In summary:
- Variable values can not be changed once assigned with value
- Final keyword variables access compile time and run time initialization
- Class level static final variables must be initialized then and there
- Class level final variables can be initialized at same line or at constructor
Comments are closed.