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

23. Use Conditional Statements

Lesson Complete

Play Next Lesson
Save for later
About this episode
See versions

See course reviews

See forum comments
Cinema mode Mark as Complete Download course materials
Previous episode: 22. Challenge: Calculate the Difference Next episode: 24. Challenge: Rewrite the Code

This video was last updated on Jul 5 2022

Lets implement the algorithm we just designed to calculate the difference between the target value and the slider value in kotlin.

As we progress, you’ll learn about conditional statements and how to use them in kotlin. The first you’ll be introduced to is the if/else statement. Let’s get started.

Before you write the actual kotlin code in the function, let’s write down the steps we’re going to take to implement the algorithm.

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.

You can also add an else if condition so:

} else if something else is true {
    then do that instead

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 blocks conditions are met.

So we have: if a condition is true, we execute that code block. Then else if we have another condition then do that instead Then 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. Convert the lines which contains the pseudo code into a comment by selecting them pressing Cmd + /. You can see that double forward slashes are added to those lines and they turn grey.

After that, declare a maximum score variable. This will hold the maximum score the player can get for a round.

val maxScore = 100

Next, you need a different varible to track the difference between the target value and the value of the slider.

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?

Okay, next you’ll set the value of difference inside an if/else statement. Go ahead and enter the following code:

if (sliderValue > targetValue) {
    difference = sliderValue - targetValue
} else if(targetValue > sliderValue) {
    difference = targetValue - sliderValue
} else {
    difference = 0

The condition goes like this:

If the sliderValue is higher than the targetValue, you subtract the targetValue from the sliderValue to get the difference.

Else if the the targetValue is greater than the sliderValue then this time around, you subtract the sliderValue from the targetValue to get the difference.

But when these conditions in the if and else if blocks are both false then it means that the targetValue and the sliderValue are equal. So the difference between both of them would be zero and that’s the situation we managed in the final else block. 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:

return maxScore - difference

You can see, this is the value that would be returned from this function. And this value is the point 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 points are displayed in the alert dialog.

Restart the activity once again to get a different target value. Then 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 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 two 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.”

We 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.

There’s another suggestion 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 syntax 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.