Final and const Keyword

/// "final" keyword : Set once but it is initialized when it is accessed.
/// "const" keyword : It is compilation time constant.
/// Const variables must be initialized with a constant value. Hence, whenever we have a value that
/// we know at compile-time and want it to be constant, we use the const keyword,
/// while if we don't know the value at compile-time and if it is to be calculated and run-time and
/// want it to be constant, we use the final keyword!
void main() {

/// 1st difference between final and const keyword
// /// Usage of "final"
// final a = 10; //"a" will not occupy memory space until we don't use of variable "a"
// print(a); //After printing OR performing action on variable(a) value, it will occupy memory space
//
// /// Usage of "const"
// const b = 22; //Here, b will occupy memory space
// print(b);

/// 2nd difference between final and const keyword
// /// Declaration of final variable
// final m = 2;
//
// /// Declaration of const variable
// const n = 5;

/// 3rd difference between final and const keyword
/// Declaration of final variable
// int x = 1, y = 2;
//
// final a = x; //here, will not give Error
// print(a);
//
// //const b = y; //here, will give Error
// const b = 2; //here, will not give Error
// print(b);

/// 4rth difference between final and const keyword
// final name; //At declaration time, Not mandatory to initialize value to variable
// name = "Rajan"; //After declaration, we can assign value to variable
// print(name);

// const book = "ExperimentOfTrue"; //At declaration time, Mandatory to initialize value to variable
// print(book); //After declaration, we can't assign value to variable

/// 5th difference between final and const keyword
final name = [
"Raman",
"Raju",
"Ramanujan",
"Rajesh",
"Aman"
];
name.add("Peter"); //we can add OR modify data in "final"
print(name);

// const name = [
// "Raman",
// "Raju",
// "Ramanujan",
// "Rajesh",
// "Aman",
// ];
// name.add("Peter"); //we can't add OR modify data in "const"
// print(name); //It will give Error on console

}

///The main difference between const and final is that const can be considered as a compile-time constant
/// while final can be considered as a run-time constant. So when you want the constant value and
/// you are aware of the value to be assigned, at the compile-time itself, you can use const!
/// But let’s say you want a constant value but you don’t know its value at compile-time,
/// then you can use final!

Comments

Popular posts from this blog

Pagination with Bloc Pattern in Flutter

Pagination First Practical in Flutter

ExpansionPanel with ExpansionPanelList with Complete Collapse Operation in Flutter