Twitter LogoFacebook Logo
If Statements
Executing code during specific condition
By: King

If statements allows you to execute code if a specific condition is met. In Kotlin, they are also referred to as expressions which means that they return a value.

Syntax

if ([condition]) {


} else if ([condition]) {

} else {

}

Examples

var temperature = 70

if (temperature > 70) {
   println("It is super hot today")
} else {
   println("It feels nice")
}

In the above example, there is an If statement that checks if the temperature is greater than 70. It if is, it will print "It is super hot today," else, it will print "It feels nice." 

var temperature = 70
var message = ""

message  = if (temperature > 70) {
   "It is super hot today"
} else {
   "It feels nice"
}

Since If statements are expressions, they can return a value. In the example, the same If statement is used, except, if the temperature is greater than 70, it will return "It is super hot today" and pass it into the message variable. If it is not, it will return "It feels nice" and that will be the new value of message.


You can also run logic inside the IF & ELSE blocks as long as the last statement in each block is a value.

var temperature = 70
var message = ""

message  = if (temperature > 70) {
    openAirConditioner()
   "It is super hot today"
} else {
   turnOffAirConditioner()
   "It feels nice"
}

Also note that if an If statement is used in conjunction with a variable, you must include the else block.

Comparison and Boolean Operators

Comparison and Boolean operators are used to add comparable logic to your code to perform specific tasks if it is met.


Comparison operators are used to compare 2 expressions. Boolean operators are used to combine 2 comparison statements.

The comparison operators available are:

<   : Less than 

>   : Greater than
<= : Less than or equal to
>= : Greater than or equal to
== : Equal to
!=  : Not equal to

The boolean operators available are:

&& - And

||    - Or
!     - Not or negation

Examples

var populationInUSA = 300000000

if (populationInUSA > 300000000) {

   println("US has over 300 million people")

} else if (populationInUSA == 250000000) {

   println("US has 250 million people")

} else if (populationInUSA > 250000000 && populationInUSA < 350000000) {

   println("The population in the US is just right")

} else {

   println("Nothing to say")

}

In the example, it used the If statement to print out a specific message when a certain condition is met. in the second else if block, it combined 2 Boolean statements with the && (AND) operator.

populationInUSA > 250000000 && populationInUSA < 350000000


Sign In