The Arrow syntax and the ternary operator

The arrow syntax is a concise and elegant way to return values in a function. 

Take, for instance, the following function. It takes an integer as an argument (value), and if value is zero, it returns false, otherwise, it returns true. So every number that you pass, except zero, will return true:

bool convertToBoolLong(int value) { 
if (value == 1) {
return false;
}
else {
return true;
}
}

With the => notation and the ternary operator, you can write the same function in a single line of code, as follows: 

bool convertToBool(int value) => (value == 0) ? false : true; 

Chances are you'll probably see this kind of syntax quite often in Dart and Flutter. 

The => arrow operator is a shortcut that allows you to simplify writing a method, particularly when it has a single return statement. Here, you can see an example of what the arrow syntax does:

In short, you could say that with the arrow syntax, you can omit the curly braces and the return statement, and instead write everything in a single line.

The ternary operator is a concise way to write an if statement. Consider the following code:

With the ternary operator, you can omit the if statement, the curly braces, and the else statement. In the optional parentheses, you put the Boolean control expression, value == 0.

Together, the arrow syntax and the ternary operator are a powerful and elegant combination.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.37.20