Kotlin tutorial for Beginners – Kotlin if Expression

Kotlin if Expression

In this article, you will learn to use if expression in Kotlin with the help of examples.

Traditional Usage of if…else

The syntax of if…else is:

if (testExpression) {
   // codes to run if testExpression is true
}
else {
  // codes to run if testExpression is false
}

if executes a certain section of code if the testExpression is evaluated to true. It can have optional else clause. Codes inside else clause are executed if the testExpression is false.


Example: Traditional Usage of if…else

fun main(args: Array<String>) {

    val number = -10

    if (number > 0) {
        print("Positive number")
    } else {
        print("Negative number")
    }
}

When you run the program, the output will be:

Negative number

Kotlin if expression

Unlike Java (and other many programming languages), if can be used an expression in Kotlin; it returns a value.


Here is an example:

Example: Kotin if expression

fun main(args: Array<String>) {

    val number = -10

    val result = if (number > 0) {
        "Positive number"
    } else {
        "Negative number"
    }

    println(result)
}

When you run the program, the output will be:

Negative number

The else branch is mandatory when using if as an expression.


The curly braces are optional if the body of if has only one statement. For example,

fun main(args: Array<String>) {
    val number = -10
    val result = if (number > 0) "Positive number" else "Negative number"
    println(result)
}

 


Example: if block With Multiple Expressions

If the block of if branch contains more than one expression, the last expression is returned as the value of the block.

fun main(args: Array<String>) {

    val a = -9
    val b = -11

    val max = if (a > b) {
        println("$a is larger than $b.")
        println("max variable holds value of a.")
        a
    } else {
        println("$b is larger than $a.")
        println("max variable holds value of b.")
        b
    }
    println("max = $max")
}

When you run the program, the output will be:

-9 is larger than -11.
max variable holds value of a.
max = -9

Recommended Reading: Kotlin when Statement


Kotlin if..else..if Ladder

You can return a block of code among many blocks in Kotlin using if..else...if ladder.


Example: if…else…if Ladder

fun main(args: Array<String>) {

    val number = 0

    val result = if (number > 0)
        "positive number"
    else if (number < 0)
        "negative number"
    else 
        "zero"
    
    println("number is $result")
}

This program checks whether number is positive number, negative number, or zero.


Kotlin Nested if Expression

An if expression can be inside the block of another if expression known as nested if expression.


Example: Nested if Expression

This program computes the largest number among three numbers.

fun main(args: Array<String>) {

    val n1 = 3
    val n2 = 5
    val n3 = -2

    val max = if (n1 > n2) {
        if (n1 > n3)
            n1
        else
            n3
    } else {
        if (n2 > n3)
            n2
        else
            n3
    }

    println("max = $max")
}

When you run the program, the output will be:

max = 5

 

 

Python Example for Beginners

Two Machine Learning Fields

There are two sides to machine learning:

  • Practical Machine Learning:This is about querying databases, cleaning data, writing scripts to transform data and gluing algorithm and libraries together and writing custom code to squeeze reliable answers from data to satisfy difficult and ill defined questions. It’s the mess of reality.
  • Theoretical Machine Learning: This is about math and abstraction and idealized scenarios and limits and beauty and informing what is possible. It is a whole lot neater and cleaner and removed from the mess of reality.

Data Science Resources: Data Science Recipes and Applied Machine Learning Recipes

Introduction to Applied Machine Learning & Data Science for Beginners, Business Analysts, Students, Researchers and Freelancers with Python & R Codes @ Western Australian Center for Applied Machine Learning & Data Science (WACAMLDS) !!!

Latest end-to-end Learn by Coding Recipes in Project-Based Learning:

Applied Statistics with R for Beginners and Business Professionals

Data Science and Machine Learning Projects in Python: Tabular Data Analytics

Data Science and Machine Learning Projects in R: Tabular Data Analytics

Python Machine Learning & Data Science Recipes: Learn by Coding

R Machine Learning & Data Science Recipes: Learn by Coding

Comparing Different Machine Learning Algorithms in Python for Classification (FREE)

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.