Leave a rating/review
Lets implement the algorithm we just designed to calculate the difference between the target value and the slider value in kotlin.
Along the way, you’ll learn about conditional statements and how to use them in kotlin.
You’ll learn about the if/else statement.
You’ve written an if statement earlier to show the AlertDialog.
Now you’ll be diving deeper into the topic of conditional statements.
But before you write the actual Kotlin code in the function, let’s write down the steps you’re going to take to implement the algorithm. You dont need to write the code. Just watch to understand.
Let’s start by checking to see if a condition is true.
We simply write the keyword if and then put the parenthesis around the condition.
if (something is true)
We then put braces around the code we want to run.
if (something is true) {
then do this
}
So here we say if something is true, we execute the code inside the curly braces. This is our first condition.
And do note that this is psuedocode and not actual Kotlin code. Pseudo code just helps us write out the steps to solve a programming task in a human friendly way using plain human language. I’m just using this for demonstration purposes.
We can then put an else if clause to check another condition.
...
} else if (something else is true) {
then do that instead
}
Do note that you can also have multiple else if blocks.
Then you can finally have an else statement at the end.
} else {
do something when neither of the above are true
}
This else statement’s block would be executed if none of the if and else if conditions are met.
And the code goes like this: if a condition is true, we execute that code block. Then else if we have another condition then do that instead Finally else if non of those conditions above are true then do something else.
And do note that the hanging else block is optional. Sometimes, we might not want to do anything when the if and else if blocks returns false.
Cool!!!
So now we’re going to write a real Kotlin if/else statement.
I’ll clear the pseudocode.
After that, declare a maximum score constant:
val maxScore = 100
This will hold the maximum score the player can get for a round. And we’re using a constant here because this value will not change.
Next, you need a different variable to track the difference between the targetValue and the sliderValue:
var difference: Int
As you can see we need to explicitly declare the type of the variable in this case Int.
And this is because we have not initialized it with a value.
So kotlin’s type inference engine cannot determine what type of data this variable will store.
But for maxScore, there was no need to add Int as the type because we initialized it with a value of 100.
So the type inference engine implicitly gives maxScore an Int data type.
If the value of maxScore had a decimal like 100.0, then the type inference engine would infer it to be a Double data type.
You get the idea, right?
Next, you’ll set the value of difference inside an if/else statement.
Go ahead and enter the following code:
if (sliderToInt > targetValue) {
difference = sliderToInt - targetValue
} else if(targetValue > sliderToInt) {
difference = targetValue - sliderToInt
} else {
difference = 0
}
Do note that we’re using sliderToInt here and not the sliderValue variable and this is because we want the percentage-based version of the sliderValue.
But while explaining, I’ll just call it slider value so you dont get confused.
Now, the condition goes like this:
-
If the slider value is higher than the
targetValue, you subtract thetargetValuefrom the slider value to get the difference. -
Else, if the
targetValueis greater than the slider value then this time around, you subtract the slider value from thetargetValueto get the difference. -
But when the conditions in the
ifandelse ifblocks are both false then it means that thetargetValueand the slider value are equal. So the difference between both of them would be zero and that’s the situation we managed in the finalelseblock. We assign a value of zero to the difference.
You can see that Android Studio complains that the difference variable is never used.
Let’s subtract the difference from the maximum score to get the points.
Enter the following code as the return statement like so:
return maxScore - difference
You can see, this is the value that would be returned from this function. And this value is the points for the round and it is an integer value.
Run your app.
Select a value close to the targetValue but below it.
Then tap “Hit Me.”
You can see the correct point is displayed in the alert dialog.
Restart the app once again to get a different target value. This time around select a value a bit higher than the target value. Then tap “Hit Me” once again. Cool!!! The correct point is displayed and we dont have a negative number as the score.
One last thing. Sometimes Android Studio gives you some suggestions to optimize your code. If you look closely at the if keyword, you can see it is underlined with yellow which shows a warning. Our code is not broken, meaning, it will work but Android studio feels we could refactor our code with a better structure.
Click on the if statement.
Then click the bulb icon.
You can see it gives us some suggestions.
It says we could use another type of conditional statement called the when statement.
It also says we can lift the assignment of the difference variable out of the if block.
This is a good suggestion because as you can see, we are assigning the difference variable multiple times.
But if we move the assignment out of the if block then the assignment would be done only once.
Go ahead and select “Lift assignment out of if.”
Now the value of the difference variable is the result of the if statement.
With this, you’ve reduced code repetition because the difference is assigned only once.
You can still go further with refactoring if you want to. Now look at how the difference variable declaration is now underlined with a warning. If you hover over it, the warning says the declaration can be joined with the assignment. Click on the suggestion on the warning that says: “Join declaration and assignment.”
You can then remove the Int type declaration we added since the type inference engine can figure out the variable type based on the result of the if statement.
We can continue refactoring but i’ll stop here. The point i’m trying to make is that there are multiple ways of doing the same thing. And Kotlin gives you different constructs to suit your needs.
I’ll stick to the initial code we wrote because this is a beginner course and it is more readable to help you grasp the concepts. Syntax can always be Googled or looked up in the documentation. You’ll learn many ways to refactor your code in Kotlin along this learning path.
So I’ll undo the changes by hitting Cmd + Z until i get to the original code.
But not to worry, you’ll keep refactoring this code in the next episode to even have less code than this.