Dart final Keyword
The final keyword is used to create objects of immutable nature. The key difference between the final and const keyword lies in their usage. The const keyword is a compile-time constant, whereas the final keyword is a run-time constant.
Implementation of Final Keyword
We can use the final keyword as follows.
Syntax:
// This syntax can be used when the data type is not known
final variable_name
// This syntax can be used when the data type is known
final [data_type] variable_name
Code:
// Dart program to demonstrate final keyword
void main(){
final String ninja_name = "Mr X"; // a variable declared as final
print("Ninja name: " + ninja_name);
// ninja_name = "Mr John X";
// If we uncomment the above statement, this will throw an error
// As the value of final variables cannot be changed
final int total_marks = get_total_marks(); // Getting the value of a final variable at runtime
print("Total marks obtained by the ninja: ${total_marks}");
}
// Demo function, just return the sum of marks in three subjects
int get_total_marks(){
int PHYSICS = 50;
int CHEMISTRY = 70;
int MATHS = 90;
return PHYSICS + CHEMISTRY + MATHS;
}
Output:
Ninja name: Mr X
Total marks obtained by the ninja: 210
Read about Batch Operating System here.
Frequently Asked Questions
How does the variable declare using the final keyword determines the type of variable it will store?
The variable declared using the final keyword determines the type of variable it will store with the help of Dart Analyzer.
What is the state of the object that is declared as const?
The state of an object that is declared with the keyword const is considered to be frozen and immutable.
Is a new const object created every time an expression involving const is evaluated?
No, the same const object is re-used every time an expression involving const is evaluated.
Conclusion
In this article, we have extensively discussed const and final keywords and sample programs having their implementation in Dart. Feel free to refer to the blog Dart Constructors and Super Constructors to learn about this topic.
We hope this blog has helped you enhance your knowledge regarding Dart const and Final keywords. If you want to learn more, check out our Android Development Course on the Coding Ninjas Website to learn everything you need to know about Android development. Do upvote our blog to help other ninjas grow. Happy Coding!