We’ve now reduced our pointsForCurrentRound() to just a few lines of code. There’s another handy feature of Dart that we haven’t really taken advantage of yet. This is called type inference.
When making or creating a variable, it’s often obvious about the variables type. For instance, when using single quotes, it’s obvious we’re working with strings. When using whole numbers, it’s obvious we’re using integers. And so on.
When we know the type, we use the var keyword instead of putting the type. By removing the type of our variable, we are removing unneeded code. The variable still keeps its type. There’s going to be times when the compiler can’t determine the type. In this case, we have to be explicit with our typing.
To get started open your project in progress or download the starter project for this episode. Open up main.dart and scroll down to our _pointsForCurrentRound method.
We’re defining two variables with their types. We have the maximum score and the difference variable. Both are ints. Yet, we can tell the maximum score is an int because it is set to 100.
The difference is a little harder to tell, but mousing over the various types used in the expression are all ints thus, the return variable is an int.
Now change both types to a var.
const var maximumScore = 100;
var difference = (_model.target - _model.current).abs();
You’ll see that maximumScore variable is producing an error. That’s because a constant cannot be a var. The var in the var keyword is short hand for variable which means changing whereas a constant means unchanging. So, a const var doesn’t make sense.
Instead, delete the var keyword, condensing our code.
const maximumScore = 100;
Now we could remove the return type from the method and Dart would be able to infer the type, but this makes it harder for other programmers so it’s a best practice to leave your types in place for methods.
And that’s it - nice job.