In this tutorial, we are going to learn something unique than other programming languages. This tutorial is all about Dart fat arrow => or shorthand syntax.
The syntax of fat arrow or shorthand syntax expression looks like this.
ReturnType FunctionName(Parameters...) => Expression;
- By using fat arrow => the curly brackets needs to be removed. Otherwise, the code editor will show you an error.
- If a function has a return type then by using a Fat arrow it is required to remove the return keyword.
Let me show you side by side. Both are the same function and will return the same value. Just a different syntax
var size = (int s) => s*2;
var size = (int s) { return s*2; }
To understand the concept with a real code example. We will consider the same examples that are done in
void main() { findPerimeter(9, 6); var rectArea = findArea(10, 6); print('The area is $rectArea'); } void findPerimeter(int length, int breadth) { var perimeter = 2 * (length * breadth); print('The perimeter is $perimeter'); } int findArea(int length, int breadth) { return length * breadth; }
The given functions can be optimized with the help of fat arrow in Dart.
void main() { findPerimeter(9, 6); var rectArea = findArea(10, 6); print('The area is $rectArea'); } void findPerimeter(int length, int breadth) => print('The perimeter is ${2 * (length * breadth)}'); int findArea(int length, int breadth) => length * breadth;
After hitting the run button we are still getting the same result.
The perimeter is 108 The area is 60
Please pay special focus on findArea function. By using fat arrow, return keyword is need to be removed.
Thank you so much. 🙂
good stuff
+1, it’s l+b…. come on bro, basic geometry
hi hello hhehehee hi how are you
Perimeter = 2*(length+breadth) = 30. Either way, the point is understood.