Leave a rating/review
At this point, you should feel pretty good about working with logical operators. You’ve seen how combining them can produce a true or false value. But what if you wanted to set a value based on the result of our logical operators? Often times, you’ll want to set a variable based on a condition.
For example, say you were going to a luncheon that had three types of deserts: cookies, sundae, or a cupcake. You set the variable based on a user’s preference.
For these, you use an if-statement. If you went through the Your First Kotlin Android App course, you should be right at home with if statements. They evaluate on a logical operator.
If the expression in the parenthesis is true, then the first pair of braces is evaluated.
You can provide many different conditions and one optional catch-all condition in the case that nothing was true. By using if statements, you can set variables based on conditions.
/*
// Starter code
val chrisGrade = 49
val meritAwardGrade = 90
*/
You’ll get started by defining a message that we want to print out to the run panel. So lets define a variable that will hold the message.
Enter the following code:
var message
Notice you have an error.
If you define a variable with just var, the compiler will have no way to determine the type.
So you need to add the type like so:
var message: String
Now’s let’s add the perfect attendance variable for Chris and set it to true.
val chrisHasPerfectAttendance = true
Then add the chrisIsMeritStudent constant.
val chrisIsMeritStudent = chrisHasPerfectAttendance && chrisGrade > meritAwardGrade
This is just like the samIsMeritStudent coonstant from the previous episode but this time around we’re doing it for Chris.
Run your code.
And we see, to no one’s surprise, that Chris’ grade is not greater than the merit award grade. So it doesn’t matter that he has perfect attendance: the value of this entire expression becomes false.
Let’s create a simple if statement to set a congratulatory String, if Chris is a merit student.
Add in the following code:
if (chrisIsMeritStudent) {
message = "Congratulations"
}
println(message)
Notice you get an error when you try to print out the message variable.
It says that the message variable must be initialized. This is because the message variable may not have a value set at that point.
If Chris isn’t a merit student, the message variable won’t be set and thus won’t have a value. We cover this in the topic known as Null Safety which you’ll learn in the third part of this course. Let’s add an else clause to set the value.
else {
message = "Keep studying"
}
By adding an else clause, you ensure that a value will be set in the message variable and thus, the error goes away. Now go ahead and run the project. In this case, Chris isn’t a merit scholar so the “Keep Studying” message is printed out.
A lot happened in this code that might get you to have some questions. Questions like why did we get an error when we actually see the message variable inside the if statement?
Like why didnt the print statement see that message was set to “Congratulations” inside the if block?
Well when you put code inside curly braces, you create something called a “Scope.”
Now what’s a scope? You might ask…
A scope is just a region in a program where an identifier can be recognized or exists. This identifier could be a variable, constant or even a function. You’ll learn about functions later on in this course.
You create a scope by wrapping code inside curly braces. The if/else statement is a perfect example of a scope. You can see that we set the message to congratulations. Now this variable assignment exists only inside the scope of the if statement. This means that outside the if statement, the message variable hasnt been assigned and that was why we had an error.
Scopes are really useful for performance, and for code clarity, as you shouldn’t create all the variables or constants at the top level scope, cluttering the very beginning of the program. Also, if there was not like scoping in programming, conditional statements like the if/else wouldnt exists as all variables and assignments would just be at the top level scope and this would cause a lot of conflicts.
Also, variables declared inside a scope are local to that scope. So for instance, if you declare a new variable inside the if block, then you can’t access it outside the if statement. You’ll learn more about scopes and see it in action as you progress in this course.
Now if you look at the code for the if/else statement, you assigned the message variable twice.
We can shorthen this and in fact, the IDE already hints us to do that.
Go ahead and hover over the if keyword.
It says: Assignment' can be lifted out of 'if'
Go ahead and click on the action.
And with this, whatever the if/else statement returns becomes the value of the message variable.
Shorter, cleaner and better, I believe.
Now, if you look closely, the message variable is only assigned once.
This means that we can change it to a constant using val.
And in fact, intelliJ Idea already hints us about this once again.
Aren’t we loved by this beautiful IDE.
Okay, let’s hover over the var keyword which has already been highlighted for us.
Then select change to val.
And the variable declaration is now updated.
You’ll be conditionally setting variables all the time.
We do it so much there’s actually a shorthand way of doing it. In other programming languages you have the ternary operator. But kotlin doesnt have one.
In fact, it doesnt need one because the if statement is an expression by default because it returns a value
just like what you did with the message variable.
That’s a shorthand way of assigning variables using conditionals.
Rememeber, the message variable is assigned to whatever the if/else statement returns.
Let me show you simpler example that could come in handy for you.
First, set a variable to hold Sam’s grade.
val samGrade = 99
Now let’s write a constant to hold the name of the better student which will either be Sam or Chris.
val betterStudent
Next, assign it based on the expression of samGrade being larger than chrisGrade using an if/else expression like so:
val betterStudent = if (samGrade > chrisGrade) "Sam" else "Chris"
With this, if the condition is true, we’ll assign Sam otherwise, we’ll assign Chris as the value of the betterStudent variable.
Now, let’s print out the result.
println(betterStudent)
Go ahead and run the project.
And Sam gets printed out as expected.
Nice work!
Now if you look closely, the betterStudent and the message assignment have a similar syntax.
They’re both if/else expressions that asssign the result of the if/else statement to the variable.
For one, you used curly braces while for the other one we assigned the values inline. You use curly braces for such expression when you have more that one line of code to execute.
Finally, you’re not just limited to if/else blocks.
You can have multiple conditions using else if blocks.
Now, what if Sam and Chris have the same grade? This means that none of them is better than the other. You express this using an else if block to accommmodate that extra condition.
I’ll paste in another version of this conditional:
val betterStudent = if (samGrade > chrisGrade) {
"Sam"
} else if (samGrade < chrisGrade) {
"Chris"
} else {
"They have equal grades!!!"
}
In here we use the else if block to check another condition. You can have multiple else if blocks.
Then if all the conditions fail, the else block is executed.