Leave a rating/review
Notes: 26. Use a Math Function
At this point, you’ve simplified your algorithm to calculate the difference down to a few lines of code.
That’s good, but we can do even better.
The Kotlin standard library gives us a bunch of math functions that can work on numbers.
One of the them is abs() function which can work on different types of numbers.
This handy function is used to get the absolute value of a number.
Both of these expression shown here evaluates to positive 42.
In this episode, you’ll finalize the revisions to the difference algorithm.
Let’s dive in!
To get started, open up your project in progress or download the starter project for this episode.
Open up the GameScreen file and head to the pointsForCurrentRound() function.
You’re going to use the abs() function which is the short for absolute value.
The absolute value is the distance from zero on the number line so the number is always positive.
But first, clean up the pointsForCurrentRound() function by updating it to the following:
fun pointsForCurrentRound(): Int {
val maxScore = 100
val difference = targetValue - sliderToInt
return maxScore - difference
}
Do note that we changed the difference variable from var to val.
Since we know that it wont be reassigned, making it a constant is the way to go.
Android studio would’ve given you a hint even if you missed that.
Now we want to get the absolute value of the targetValue minus the slider value.
To do that you’ll call the abs() function and pass in the calculation as the argument to get the absolute value of the difference.
Add it in like so:
val difference = abs(targetValue - sliderToInt)
And make sure you import the abs() function that accepts an Integer value as its argument from the Kotlin standard math library.
When this line is evaluated, the slider value is subtracted from the targetValue.
After which, the abs function takes the resulting number, be it positive or negative and then returns the positive value.
Run your app to try it out
And that’s it!!!
You’ve simplified the code for calculating the difference down to one line and made it easier to read in the process. That’s an absolute win. No pun intended :]