Your First Kotlin Android App: An App From Scratch

Jul 5 2022 Kotlin 1.6, Android 12, Android Studio Bumblebee | 2021.1.1

Part 3: Coding in Kotlin

25. Use a Math Method

Episode complete

Play next episode

Save for later
About this episode
See versions

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 24. Challenge: Rewrite the Code Next episode: 26. Conclusion

This video Use a Math Method was last updated on Jul 5 2022

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 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 MainActivity class and scroll down to the pointsForCurrentRound() method.

You’re going to use a method called abs 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:

private fun pointsForCurrentRound(): Int {
    val maxScore = 100
    val difference = targetValue - sliderValue
    return maxScore - difference

Do note that we changed the difference variable from var to val since we know that this variable wont be reassigned. 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 sliderValue. 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. Just like this:

val difference = abs(targetValue - sliderValue)

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 sliderValue 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 :]