Kotlin Help

Conditions and loops, if expression.

In Kotlin, if is an expression: it returns a value. Therefore, there is no ternary operator ( condition ? then : else ) because ordinary if works fine in this role.

Branches of an if expression can be blocks. In this case, the last expression is the value of a block:

If you're using if as an expression, for example, for returning its value or assigning it to a variable, the else branch is mandatory.

When expression

when defines a conditional expression with multiple branches. It is similar to the switch statement in C-like languages. Its simple form looks like this.

when matches its argument against all branches sequentially until some branch condition is satisfied.

when can be used either as an expression or as a statement. If it is used as an expression, the value of the first matching branch becomes the value of the overall expression. If it is used as a statement, the values of individual branches are ignored. Just like with if , each branch can be a block, and its value is the value of the last expression in the block.

The else branch is evaluated if none of the other branch conditions are satisfied.

If when is used as an expression , the else branch is mandatory, unless the compiler can prove that all possible cases are covered with branch conditions, for example, with enum class entries and sealed class subtypes).

In when statements , the else branch is mandatory in the following conditions:

when has a subject of a Boolean , enum , or sealed type, or their nullable counterparts.

branches of when don't cover all possible cases for this subject.

To define a common behavior for multiple cases, combine their conditions in a single line with a comma:

You can use arbitrary expressions (not only constants) as branch conditions

You can also check a value for being in or !in a range or a collection:

Another option is checking that a value is or !is of a particular type. Note that, due to smart casts , you can access the methods and properties of the type without any extra checks.

when can also be used as a replacement for an if - else if chain. If no argument is supplied, the branch conditions are simply boolean expressions, and a branch is executed when its condition is true:

You can capture when subject in a variable using following syntax:

The scope of variable introduced in when subject is restricted to the body of this when .

The for loop iterates through anything that provides an iterator. This is equivalent to the foreach loop in languages like C#. The syntax of for is the following:

The body of for can be a block.

As mentioned before, for iterates through anything that provides an iterator. This means that it:

has a member or an extension function iterator() that returns Iterator<> , which:

has a member or an extension function next()

has a member or an extension function hasNext() that returns Boolean .

All of these three functions need to be marked as operator .

To iterate over a range of numbers, use a range expression :

A for loop over a range or an array is compiled to an index-based loop that does not create an iterator object.

If you want to iterate through an array or a list with an index, you can do it this way:

Alternatively, you can use the withIndex library function:

While loops

while and do-while loops execute their body continuously while their condition is satisfied. The difference between them is the condition checking time:

while checks the condition and, if it's satisfied, executes the body and then returns to the condition check.

do-while executes the body and then checks the condition. If it's satisfied, the loop repeats. So, the body of do-while executes at least once regardless of the condition.

Break and continue in loops

Kotlin supports traditional break and continue operators in loops. See Returns and jumps .

  • Español – América Latina
  • Português – Brasil
  • Tiếng Việt

Write conditionals in Kotlin

1. before you begin.

Conditionals are one of the most important foundations of programming. Conditionals are commands in programming languages that handle decisions. With conditionals, code is dynamic, which means that it can behave differently given a different condition.

This codelab teaches you how to use the if/else and when statements and expressions to write conditionals in Kotlin.

Prerequisites

  • Knowledge of Kotlin programming basics, including variables, and the println() and main() functions

What you'll learn

  • How to write boolean expressions.
  • How to write if/else statements.
  • How to write when statements.
  • How to write if/else expressions.
  • How to write when expressions.
  • How to use commas to define common behavior for multiple branches in when conditionals.
  • How to use the in range to define common behavior for a range of branches in when conditionals.
  • How to use the is keyword to write when conditional statements.

What you'll need

  • A web browser with access to Kotlin Playground

2. Use if/else statements to express conditions

In life, it's common to do things differently based on the situation that you face. For example, if the weather is cold, you wear a jacket, whereas if the weather is warm, you don't wear a jacket.

A flowchart that describes a decision that's made when the weather is cold. A yes arrow points to

Decision-making is also a fundamental concept in programming. You write instructions about how a program should behave in a given situation so that it can act or react accordingly when the situation occurs. In Kotlin, when you want your program to perform different actions based on a condition, you can use an if/else statement. In the next section, you write an if statement.

Write if conditions with boolean expressions

Imagine that you build a program that tells drivers what they should do when they're at a traffic light. Focus on the first condition: a red traffic light. What do you do at a red traffic light? Stop!

A flowchart that describes a decision made when the traffic-light color is red. A yes arrow points to a

In Kotlin, you can express this condition with an if statement. Take a look at the anatomy of an if statement:

A diagram that describes an if statement with the if keyword followed by a pair of parentheses with a condition inside them. After that, there's a pair of curly braces with a body in them. The condition block is highlighted.

To use if statements, you need to use the if keyword followed by the condition that you want to evaluate. You need to express the condition with a boolean expression. Expressions combine values, variables, and operators that return a value. Boolean expressions return a boolean value.

Previously, you learned about assignment operators , such as:

The = assignment operator assigns the number variable a 1 value.

In contrast, boolean expressions are constructed with comparison operators , which compare values or variables on both sides of the equation. Take a look at a comparison operator.

The == comparison operator compares the values to each other. Which boolean value do you think this expression returns?

Find the boolean value of this expression:

  • Use Kotlin Playground to run your code.
  • In the function body, add a println() function and then pass it the 1 == 1 expression as an argument:
  • Run the program and then view the output:

The first 1 value is equal to the second 1 value, so the boolean expression returns a true value, which is a boolean value.

Besides the == comparison operator, there are additional comparison operators that you can use to create boolean expressions:

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

Practice the use of comparison operators with simple expressions:

  • In the argument, replace the == comparison operator with the < comparison operator:

The output returns a false value because the first 1 value isn't less than the second 1 value.

  • Repeat the first two steps with the other comparison operators and numbers.

Write a simple if statement

Now that you saw a few examples of how to write boolean expressions, you can write your first if statement. The syntax for an if statement is as follows:

A diagram that describes an if statement with the if keyword followed by a pair of parentheses with a condition inside them. After that, there's a pair of curly braces with a body inside them. The body block is highlighted.

An if statement starts with the if keyword followed by a condition, which is a boolean expression inside parentheses and a set of curly braces. The body is a series of statements or expressions that you put inside a pair of curly braces after the condition. These statements or expressions only execute when the condition is met. In other words, the statements within the curly braces only execute when a boolean expression in the if branch returns a true value.

Write an if statement for the red traffic-light condition:

  • Inside the main() function, create a trafficLightColor variable and assign it a "Red" value:
  • Add an if statement for the red traffic-light condition and then pass it a trafficLightColor == "Red" expression:
  • In the body of the if statement, add a println() function and then pass it a "Stop" argument:

The trafficLightColor == "Red" expression returns a true value, so the println("Stop") statement is executed, which prints the Stop message.

A diagram that highlights the if statement of trafficLightColor ==

Add an else branch

Now you can extend the program so that it tells drivers to go when the traffic light isn't red.

A flowchart that describes a decision made when the traffic-light color is red. A yes arrow points to a

You need to add an else branch to create an if/else statement. A branch is an incomplete part of code that you can join to form statements or expressions. An else branch needs to follow an if branch.

A diagram that describes an if/else statement with the if keyword followed by parentheses with a condition inside them. After that, there's a pair of curly braces with body 1 inside them followed by an else keyword followed by parentheses. After that, there's a pair of curly braces with a body 2 block inside them.

After the closing curly brace of the if statement, you add the else keyword followed by a pair of curly braces. Inside the curly braces of the else statement, you can add a second body that only executes when the condition in the if branch is false.

Add an else branch to your program:

  • After the closing curly brace of the if statement, add the else keyword followed by another pair of curly braces:
  • Inside the else keyword's curly braces, add a println() function and then pass it a "Go" argument:
  • Run this program and then view the output:

The program still behaves the same way as it did before you added the else branch, but it doesn't print a Go message.

  • Reassign the trafficLightColor variable to a "Green" value because you want drivers to go on green:

As you can see, now the program prints a Go message instead of a Stop message.

A diagram that highlights the if/else statement with the trafficLightColor ==

You reassigned the trafficLightColor variable to a "Green" value, so the trafficLightColor == "Red" expression evaluated in the if branch returns a false value because the "Green" value isn't equal to the "Red" value.

As a result, the program skips all statements in the if branch and instead executes all statements inside the else branch. This means that the println("Go") function is executed, but the println("Stop") function isn't executed.

Add an else if branch

Typically, a traffic light also has a yellow color that tells drivers to proceed slowly. You can expand the program's decision-making process to reflect this.

A flowchart that describes a decision made when the traffic-light color is red. A yes arrow points to a

You learned to write conditionals that cater to a single decision point with if/else statements that contain a single if and a single else branch. How can you handle more complex branching with multiple decision points? When you face multiple decision points, you need to create conditionals with multiple layers of conditions, which you can do when you add else if branches to if/else statements.

After the closing curly brace of the if branch, you need to add the else if keyword. Inside the parentheses of the else if keyword, you need to add a boolean expression as the condition for the else if branch followed by a body inside a pair of curly braces. The body is only executed if condition 1 fails, but condition 2 is satisfied.

A diagram that describes an if/else statement with the if keyword followed by parentheses with a condition 1 block inside them. After that, there's a pair of curly braces with a body 1 inside them.   That's followed by an else if keyword with parentheses with a condition 2 block in them. It's then followed with a pair of curly braces with a body 2 block inside them.  That's then followed by an else keyword with another pair of curly braces with a body 3 block inside them.

The else if branch is always located after the if branch, but before the else branch. You can use multiple else if branches in a statement:

A diagram that shows an if/else condition with multiple else if branches between the if and else branches. A text annotated around the else if branches state that there's multiple else if branches.

The if statement can also contain the if branch and else if branches without any else branch:

A diagram that describes an if/else statement with the if keyword followed by parentheses with a condition 1 block inside them. After that, there's a pair of curly braces with a body 1 inside them.   That's followed by an else if keyword with parentheses and a condition 2 block inside them. It's then followed with a pair of curly braces with a body 2 block inside them.

Add an else if branch to your program:

  • After the closing curly brace of the if statement, add an else if (trafficLightColor == "Yellow") expression followed by curly braces:
  • Inside the curly braces of the else if branch, add a println() statement and then pass it a "Slow" string argument:
  • Reassign the trafficLightColor variable to a "Yellow" string value:

Now the program prints a Slow message, instead of a Stop or Go message.

A diagram that highlights the if/else statement with the trafficLightColor ==

Here's why it only prints a Slow message and not the other lines:

  • The trafficLightColor variable is assigned a "Yellow" value.
  • The "Yellow" value isn't equal to the "Red" value, so the boolean expression of the if branch (denoted as 1 in the image) returns a false value. The program skips all statements inside the if branch and doesn't print a Stop message.
  • Since the if branch yields a false value, the program proceeds to evaluate the boolean expression inside the else if branch.
  • The "Yellow" value is equal to the "Yellow" value, so the boolean expression of the else if branch (denoted as 2 in the image) returns a true value. The program executes all statements inside the else if branch and prints a Slow message.
  • Since the boolean expression of the else if branch returns a true value, the program skips the rest of the branches. Thus, all statements in the else branch aren't executed and the program doesn't print a Go message.

Have you noticed that the current program contains a bug?

In Unit 1, you learned about a type of bug called a compile error in which Kotlin can't compile the code due to a syntactical error in your code and the program can't run. Here, you face another type of bug called a logic error in which the program can run, but doesn't produce an output as intended.

Supposedly, you only want drivers to drive only when the traffic-light color is green. What if the traffic light is broken and turned off? Would you want the driver to drive or receive a warning that something is wrong?

Unfortunately, in the current program, if the traffic-light color is anything else other than red or yellow, the driver is still advised to go .

Fix this problem:

  • Reassign the trafficLightColor variable to a "Black" value to illustrate a traffic light that is turned off:

Notice that the program prints a Go message even though the trafficLightColor variable isn't assigned a "Green" value. Can you fix this program so that it reflects the correct behavior?

A flowchart that describes a decision made when the traffic-light color is red. A yes arrow points to a

You need to modify the program so that it prints:

  • A Go message only when the trafficLightColor variable is assigned a "Green" value.
  • An Invalid traffic-light color message when the trafficLightColor variable isn't assigned a "Red" , "Yellow" , or "Green" value.

Fix the else branch

The else branch is always located at the end of an if/else statement because it's a catchall branch. It automatically executes when all other conditions in the preceding branches aren't satisfied. As such, the else branch isn't suitable when you want an action to execute only when it satisfies a specific condition. In the case of the traffic light, you can use the else if branch to specify the condition for green lights.

Use the else if branch to evaluate the green traffic-light condition:

  • After the current else if branch, add another else if (trafficLightColor == "Green") branch:
  • Run this program and then view the output.

The output is empty because you don't have an else branch that executes when the previous conditions aren't satisfied.

  • After the last else if branch, add an else branch with a println("Invalid traffic-light color") statement inside:
  • Assign the trafficLightColor variable another value besides "Red" , "Yellow" , or "Green" and then rerun the program.

What's the output of the program?

It's good programming practice to have an explicit else if branch as input validation for the green color and an else branch to catch other invalid inputs. This ensures that drivers are directed to go , only when the traffic light is green. For other cases, there's an explicit message relayed that the traffic light isn't behaving as expected.

3. Use a when statement for multiple branches

Your trafficLightColor program looks more complex with multiple conditions, also known as branching. You may wonder whether you can simplify a program with an even larger number of branches.

In Kotlin, when you deal with multiple branches, you can use the when statement instead of the if/else statement because it improves readability, which refers to how easy it is for human readers, typically developers, to read the code. It's very important to consider readability when you write your code because it's likely that other developers need to review and modify your code throughout its lifetime. Good readability ensures that developers can correctly understand your code and don't inadvertently introduce bugs into it.

when statements are preferred when there are more than two branches to consider.

A diagram that shows the anatomy of a when statement. It starts with a when keyword followed by a pair of curly braces with a parameter block inside them. Next, inside a pair curly braces, there are three lines of cases. Inside each line, there's a condition block followed by an arrow symbol and a body block. It's noted that each of the lines of cases are evaluated sequentially.

A when statement accepts a single value through the parameter. The value is then evaluated against each of the conditions sequentially. The corresponding body of the first condition that's met is then executed. Each condition and body are separated by an arrow ( -> ). Similar to if/else statements, each pair of condition and body is called a branch in when statements. Also similar to the if/else statement, you can add an else branch as your final condition in a when statement that works as a catchall branch.

Rewrite an if/else statement with a when statement

In the traffic-light program, there are already multiple branches:

  • Red traffic-light color
  • Yellow traffic-light color
  • Green traffic-light color
  • Other traffic-light color

Convert the program to use a when statement:

  • In the main() function, remove the if/else statement:
  • Add a when statement and then pass it the trafficLightColor variable as an argument:
  • In the body of the when statement, add the "Red" condition followed by an arrow and a println("Stop") body:
  • On the next line, add the "Yellow" condition followed by an arrow and a println("Slow") body:
  • On the next line, add the "Green" condition followed by an arrow and then a println("Go") body:
  • On the next line, add the else keyword followed by an arrow and then a println("Invalid traffic-light color") body:
  • Reassign the trafficLightColor variable to a "Yellow" value:

When you run this program, what do you think the output will be?

7112edfc7c7b7918.png

The output is a Slow message because:

  • The program evaluates each condition one-by-one in sequence.
  • The "Yellow" value isn't equal to the "Red" value, so the program skips the first body.
  • The "Yellow" value is equal to the "Yellow" value, so the program executes the second body and prints a Slow message.
  • A body was executed, so the program ignores the third and fourth branches, and leaves the when statement.

Write more complex conditions in a when statement

So far you learned how to write when conditions for a single equal condition, such as when the trafficLightColor variable is assigned a "Yellow" value. Next, you learn to use the comma ( , ), the in keyword, and the is keyword to form more complex when conditions.

Build a program that determines whether a number between 1 and 10 is a prime number:

  • Open Kotlin playground in a separate window.

You return to the traffic-light program later.

  • Define an x variable and then assign it a 3 value:
  • Add a when statement that includes multiple branches for 2 , 3 , 5 and 7 conditions and follow each with a println("x is prime number between 1 and 10.") body:
  • Add an else branch with a println("x is not prime number between 1 and 10.") body:
  • Run the program and then verify that the output is as expected:

Use a comma ( , ) for multiple conditions

The prime-number program contains a lot of repetition of println() statements. When you write a when statement, you can use a comma ( , ) to denote multiple conditions that correspond to the same body.

A diagram that shows the anatomy of a when statement. It starts with a when keyword followed by parentheses with a parameter block inside them. Next, inside a pair curly braces, there are two lines of cases. On the first line, there's a condition 1 block followed by a comma, followed by a condition 2 block followed by an arrow symbol and a body block. On the second line, there's a condition block followed by an arrow symbol and a body block.

In the previous diagram, if either the first or second condition is fulfilled, the corresponding body is executed.

Rewrite the prime number program with this concept:

  • In the branch for the 2 condition, add 3 , 5 and 7 separated by commas ( , ):
  • Remove the individual branches for the 3 , 5 and 7 conditions:

Use the in keyword for a range of conditions

Besides the comma ( , ) symbol to denote multiple conditions, you can also use the in keyword and a range of values in when branches.

A diagram that shows the anatomy of a when statement. It starts with a when keyword followed by parentheses with a parameter block inside them. Next, inside a pair curly braces, there are two lines of cases. On the first line, there's an in keyword followed by a range start block, two dots, a range end block, an arrow symbol, and then a body block. On the second line, there's a condition block followed by an arrow symbol and a body block.

To use a range of values, add a number that denotes the start of the range followed by two periods without any spaces and then close it with another number that denotes the end of the range.

When the value of the parameter is equal to any value in the range between start of the range and the end of the range, the first body executes.

In your prime-number program, can you print a message if the number is between 1 and 10, but not a prime number?

Add another branch with the in keyword:

  • After the first branch of the when statement, add a second branch with the in keyword followed by a 1..10 range and a println("x is a number between 1 and 10, but not a prime number.") body:
  • Change the x variable to a 4 value:
  • Run the program and then verify the output:

The program prints the message of the second branch, but not the message of the first or third branch.

Here's how this program works:

  • The x variable is assigned a 4 value.
  • The program proceeds to evaluate conditions for the first branch. The 4 value isn't the 2 , 3 , 5 , or 7 values, so the program skips the execution of the body of the first branch and proceeds to the second branch.
  • The 4 value is between 1 and 10 , so the message of x is a number between 1 and 10, but not a prime number. body is printed.
  • One body is executed, so the program proceeds to leave the when statement and ignores the else branch.

Use the is keyword to check data type

You can use the is keyword as a condition to check the data type of an evaluated value.

A diagram that shows the anatomy of a when statement. It starts with a when keyword followed by parentheses with a parameter block inside them. Next, inside a pair curly braces, there are two lines of cases. On the first line, there is an in keyword followed by a type block, an arrow symbol, and  then a body block. On the second line, there's a condition block followed by an arrow symbol and then a body block.

In the previous diagram, if the value of the argument is of the data type stated, the first body is executed.

In your prime-number program, can you print a message if the input is an integer number that's outside the range of 1 to 10?

Add another branch with the is keyword:

  • Modify x to be of type Any . This is to indicate that x can be of value other than Int type.
  • After the second branch of the when statement, add the is keyword and an Int data type with a println("x is an integer number, but not between 1 and 10.") body:
  • In the else branch, change the body to a println("x isn't an integer number.") body:
  • Change the x variable to a 20 value:

The program prints the message of the third branch, but not the messages of the first, second, or fourth branches.

1255c101845f9247.png

Here's how the program works:

  • The x variable is assigned a 20 value.
  • The program proceeds to evaluate conditions for the first branch. The 20 value isn't the 2 , 3 , 5 or 7 values, so the program skips the execution of the body of the first branch and proceeds to the second branch.
  • The 20 value isn't inside the 1 to 10 range, so the program skips the execution of the body of the second branch and proceeds to the third branch.
  • The 20 value is of Int type, so the x is an integer number, but not between 1 and 10 body is printed.

Now practice what you learned in your traffic-light program.

Imagine that there's an amber traffic-light color in some countries that warns drivers the same way as a yellow traffic light in other countries. Can you modify the program so that this additional condition is covered and maintain the original conditions?

Add an additional condition with the same body

Add an additional condition to the traffic-light program:

  • If you still have it open, go back to the instance of Kotlin Playground with your traffic-light program.
  • If you closed it, open a new instance of Kotlin Playground and enter this code:
  • In the second branch of the when statement, add a comma after the "Yellow" condition and then an "Amber" condition:
  • Change the trafficLightColor variable to an "Amber" value:
  • Run this program and then verify the output:

4. Use if/else and when as expressions

You learned how to use if/else and when as statements. When you use conditionals as statements, you let each branch execute different actions in the body based on the conditions.

You can also use conditionals as expressions to return different values for each branch of condition. When the body of each branch appears similar, you can use conditional expressions to improve code readability compared to conditional statements.

A diagram that describes an if/else expression with the val keyword followed by a name block, an equal symbol, an if keyword, parentheses with a condition inside them, a pair of curly braces with a body 1 block inside them, an else keyword, and then a pair of curly braces with a body block inside them.

The syntax for conditionals as expressions is similar to statements, but the last line of bodies in each branch need to return a value or an expression, and the conditionals are assigned to a variable.

If the bodies only contain a return value or expression, you can remove the curly braces to make the code more concise.

A diagram that describes an if/else expression with the val keyword followed by a name block, an equal symbol, an if keyword,  parentheses with a condition inside them, an expression 1 block, an else keyword, and then an expression 2 block.

In the next section, you take a look at if/else expressions through the traffic-light program.

Convert an if statement to an expression

There's a lot of println() statement repetition in this if/else statement:

Convert this if/else statement to an if/else expression and remove this repetition:

  • In Kotlin playground, enter the previous traffic-light program.
  • Define a message variable and then assign it an if/else statement:
  • Remove all println() statements and their curly braces, but leave the values inside them:
  • Add a println() statement to the end of the program and then pass it the message variable as an argument:

Convert the traffic-light program to use a when expression instead of a when statement:

  • In Kotlin Playground, enter this code:

Can you convert the when statement to an expression so that you don't repeat the println() statements?

  • Create a message variable and assign it to the when expression:
  • Add a println() statement as the last line of the program and then pass it the message variable as an argument:

5. Conclusion

Congratulations! You learned about conditionals and how to write them in Kotlin.

  • In Kotlin, branching can be achieved with if/else or when conditionals.
  • The body of an if branch in an if/else conditional is only executed when the boolean expression inside the if branch condition returns a true value.
  • Subsequent else if branches in an if/else conditional get executed only when previous if or else if branches return false values.
  • The final else branch in an if/else conditional only gets executed when all previous if or else if branches return false values.
  • It's recommended to use the when conditional to replace an if/else conditional when there are more than two branches.
  • You can write more complex conditions in when conditionals with the comma ( , ), in ranges, and the is keyword.
  • if/else and when conditionals can work as either statements or expressions.
  • Conditions and loops

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License , and code samples are licensed under the Apache 2.0 License . For details, see the Google Developers Site Policies . Java is a registered trademark of Oracle and/or its affiliates.

Learn Python practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn python interactively, kotlin introduction.

  • Kotlin Hello World
  • Kotlin Data Types
  • Kotlin Operators
  • Kotlin Type Conversion
  • Kotlin Expression & Statement
  • Kotlin Comments
  • Kotlin Input/Output

Kotlin Flow Control

Kotlin if expression.

Kotlin when Expression

  • Kotlin while Loop
  • Kotlin for Loop
  • Kotlin break
  • Kotlin continue

Kotlin Functions

  • Kotlin function
  • Infix Function Call
  • Default and Named Arguments
  • Recursion and Tail Recursion
  • Kotlin Class and Objects
  • Kotlin Constructors
  • Kotlin Getters and Setters
  • Kotlin Inheritance
  • Kotlin Visibility Modifiers
  • Kotlin Abstract Class
  • Kotlin Interfaces
  • Kotlin Nested and Inner Classes
  • Kotlin Data Class
  • Kotlin Sealed Class
  • Kotlin Object
  • Kotlin Companion Objects
  • Kotlin Extension Function
  • Kotlin Operator Overloading

Kotlin Tutorials

Kotlin Expression, Statements and Blocks

  • Check Whether a Number is Positive or Negative

Kotlin break Expression

Kotlin while and do...while Loop

  • Check Whether a Number is Even or Odd

Kotlin if Expression

Traditional usage of if...else.

The syntax of if...else is:

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

When you run the program, the output will be:

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

Here is an example:

Example: Kotin if expression

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,

This is similar to ternary operator in Java . Hence, there is no ternary operator in Kotlin.

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.

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

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.

Table of Contents

  • Example: if expression
  • Example: if block with multiple expressions
  • Kotlin if...else..if Ladder

Sorry about that.

Related Tutorials

Kotlin Tutorial

Collections

  • Android Studio
  • Kotlin Android
  • Android Projects
  • Android Interview Questions
  • Kotlin Tutorial
  • Introduction to Kotlin
  • Kotlin Environment setup for Command Line
  • Kotlin Environment setup with Intellij IDEA
  • Hello World program in Kotlin
  • Kotlin Data Types
  • Kotlin Variables
  • Kotlin Operators
  • Kotlin Standard Input/Output
  • Kotlin Type Conversion
  • Kotlin Expression, Statement and Block

Control Flow

Kotlin if-else expression.

  • Kotlin while loop
  • Kotlin do-while loop
  • Kotlin for loop
  • Kotlin when expression
  • Kotlin Unlabelled break
  • Kotlin labelled continue

Array & String

  • Kotlin Array
  • Kotlin String
  • Kotlin functions
  • Kotlin | Default and Named argument
  • Kotlin Recursion
  • Kotlin Tail Recursion
  • Kotlin | Lambdas Expressions and Anonymous Functions
  • Kotlin Inline Functions
  • Kotlin infix function notation
  • Kotlin Higher-Order Functions
  • Kotlin Collections
  • Kotlin list : Arraylist
  • Kotlin list : listOf()
  • Kotlin Set : setOf()
  • Kotlin hashSetOf()
  • Kotlin Map : mapOf()
  • Kotlin Hashmap

OOPs Concept

  • Kotlin Class and Objects
  • Kotlin Nested class and Inner class
  • Kotlin Setters and Getters
  • Kotlin | Class Properties and Custom Accessors
  • Kotlin Constructor
  • Kotlin Visibility Modifiers
  • Kotlin Inheritance
  • Kotlin Interfaces
  • Kotlin Data Classes
  • Kotlin Sealed Classes
  • Kotlin Abstract class
  • Enum Classes in Kotlin
  • Kotlin extension function
  • Kotlin generics

Exception Handling

  • Kotlin Exception Handling | try, catch, throw and finally
  • Kotlin Nested try block and multiple catch block

Null Safety

  • Kotlin Null Safety
  • Kotlin | Type Checking and Smart Casting
  • Kotlin | Explicit type casting

Regex & Ranges

  • Kotlin Regular Expression
  • Kotlin Ranges

Java Interoperability

  • Java Interoperability - Calling Kotlin from Java
  • Java Interoperability - Calling Java from Kotlin

Miscellaneous

  • Kotlin annotations
  • Kotlin Reflection
  • Kotlin Operator Overloading
  • Destructuring Declarations in Kotlin
  • Equality evaluation in Kotlin
  • Comparator in Kotlin
  • Triple in Kotlin
  • Pair in Kotlin
  • Kotlin | apply vs with
  • Kotlin for Android Tutorial
  • How to create project in Android Studio using Kotlin
  • How to Install Android Virtual Device(AVD)?
  • Android Animations in Kotlin
  • Android Fade In/Out in Kotlin
  • Android Menus
  • Android progress notifications in Kotlin
  • Android Project folder Structure

Decision Making in programming is similar to decision-making in real life. In programming too, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of a program based on certain conditions. If the condition is true then it enters into the conditional block and executes the instructions.  There are different types of if-else expressions in Kotlin: 

  • if expression
  • if-else expression
  • if-else-if ladder expression
  • nested if expression

if statement:  

It is used to specify whether a block of statements will be executed or not, i.e. if a condition is true, then only the statement or block of statements will be executed otherwise it fails to execute.

Syntax:   

Flowchart:   

if else assignment kotlin

Example:   

Output:  

if-else statement: 

if-else statement contains two blocks of statements. ‘if’ statement is used to execute the block of code when the condition becomes true and ‘else’ statement is used to execute a block of code when the condition becomes false. 

if else assignment kotlin

Here is the Kotlin program to find the larger value of two numbers. 

Example:  

Kotlin if-else expression as ternary operator:

In Kotlin, if-else can be used as an expression because it returns a value. Unlike java, there is no ternary operator in Kotlin because if-else returns the value according to the condition and works exactly similar to ternary. 

Below is the Kotlin program to find the greater value between two numbers using if-else expression. 

if-else-if ladder expression: 

Here, a user can put multiple conditions. All the ‘if’ statements are executed from the top to bottom. One by one all the conditions are checked and if any of the conditions is found to be true then the code associated with the if statement will be executed and all other statements bypassed to the end of the block. If none of the conditions is true, then by default the final else statement will be executed. 

if else assignment kotlin

Below is the Kotlin program to determine whether the number is positive, negative, or equal to zero.  

nested if expression: 

Nested if statements mean an if statement inside another if statement. If the first condition is true then code the associated block to be executed, and again check for the if condition nested in the first block and if it is also true then execute the code associated with it. It will go on until the last condition is true. 

Syntax:   

if else assignment kotlin

Below is the Kotlin program to determine the largest value among the three Integers. 

Please Login to comment...

Similar reads.

  • How to Use ChatGPT with Bing for Free?
  • 7 Best Movavi Video Editor Alternatives in 2024
  • How to Edit Comment on Instagram
  • 10 Best AI Grammar Checkers and Rewording Tools
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Kotlin Tutorial – Learn to program with simple examples

online free

  • Why learn Kotlin?
  • Where and how can you learn Kotlin?
  • Installing the development environment and setting up the first Kotlin project
  • Program structure
  • Variables in Kotlin
  • Data types in Kotlin
  • Input/Output (IO) in Kotlin
  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Bitwise operators in Kotlin

Conditional statements

  • Loops in Kotlin
  • Areas in Kotlin
  • Arrays in Kotlin
  • Functions in Kotlin
  • Variable number of arguments in a function
  • return – Return a value from a function
  • Single Expression Functions
  • Local functions in Kotlin
  • Signatures and function overloads
  • Function types
  • Store functions in variables
  • Higher order functions
  • Anonymous functions
  • Lambda functions in Kotlin
  • Standard functions for working with strings
  • Standard mathematical functions in Kotlin
  • Standard functions for arrays in Kotlin
  • Standard date and time functions
  • Introduction to OOP
  • Kotlin Playground

In programming, conditional statements are constructs that make it possible to control a program flow based on conditions. The condition can, for example, refer to a specific variable or the state of a program. If the condition is met, the code within the conditional statement is executed. Otherwise the code is skipped or an alternative code block is executed.

There are two types of conditional statements in Kotlin: if statements and when expressions .

The if statement allows an action to be performed if a condition is true. The syntax of the if statement is similar to other programming languages, but there are some differences.

The general syntax of if statement in Kotlin is as follows:

Here is a simple example:

This code defines a variable called number with the value 10. Then a conditional statement is introduced with the if statement. The condition is number > 5 , which means that the code block inside the curly braces will only be executed if the variable number greater than 5 is. In this case that is the case, there number the value 10  has that is greater than 5   is. Therefore, the code inside the curly braces is executed and the output “The number is greater than 5” is printed on the console.

Basically, if the code block consists of only one expression, the curly braces can be omitted:

The if-else statement allows one of two blocks of code to be executed depending on whether a condition is true or false. The syntax of if-else statement in Kotlin is as follows:

This code defines a variable called age with the value 18 . Then a conditional statement with the if -Instruction initiated. The condition is age > = 18 , which means that the block of code inside the curly braces will only be executed if the person's age is 18 or older. In this case that is the case because age is the value 18 has, which means that the person is of legal age. Therefore, the code inside the first curly braces is executed and the output “You are of legal age” is printed on the console. If the condition is false (i.e. the person's age is under 18), the code within the else statement executed and the output “You are a minor” is printed on the console.

The if statement can also return a value. For example, we can find the maximum of two numbers:

If additional actions need to be performed to determine the returned value, these actions can be placed in code blocks:

At the end of each block the returned value is specified.

Kotlin also has that if-else-if statement , which allows checking multiple conditions and executing different blocks of code depending on the conditions. The syntax for the if-else-if statement is as follows:

Here is an example of using the if-else-if statement to determine the grading system based on the score:

When is a conditional statement in Kotlin that allows checking a variety of conditions and executing the corresponding block of code associated with the appropriate condition.

Here is an example of using when to determine the day of the week based on the day of the week:

Comparison with group of values

A comparison can be made with a group of values. It is possible to define the same actions for several of these values ​​at the same time. In this case the values ​​are listed separated by commas,

You can also compare a value to a whole range of values ​​using the in operator .

If the in operator makes it possible to find out whether a value is within a certain range, the combination of operators allows !in checking whether a value is not contained in a specific sequence.

when expression and dynamically calculated values

The when expression can also be compared with dynamically calculated values.

When can also accept a dynamically calculated object.

It is even possible to define variables that will be available within the when expression.

The construction When can also be used as an alternative to if..else be used. The value of an object does not necessarily have to be compared. Instead, a series of conditions are checked. Once one of the conditions returns true, the associated set of statements is executed.

Similar to the if construct, the when expression return a value. The result returned is through the arrow operator -> Are defined.

  • ← Bitwise operators in Kotlin
  • Loops in Kotlin →
  • < Previously. Article
  • Next. Article >

Leave a Comment Cancel reply

Your e-mail address will not be published. Required fields are marked with * marked

Save my name, email and website in this browser for the next time I comment.

The Kotlin Primer

The Kotlin Primer

  • 🚙 · If expression

Read on to find out how if / else acts as a replacement for the ternary operator in Kotlin.

There is no ternary operator (i.e.  <condition> ? <then> : <else> ) in Kotlin. Instead,  if/else  may be used as an expression:

  • if  is an expression here — it returns a value. You can wrap each branch in  {   }  if you need it to contain multiple statements.

This is actually much more powerful than the ternary operator, because you can also use  else if  branches:

In Java, you would need to nest the ternary operator, which quickly gets out of hand:

Leave a Comment Cancel reply

Remember me (does not create account)

This site uses Akismet to reduce spam. Learn how your comment data is processed .

  • 💡 · Understanding the Kotlin Primer
  • 💡 · Maintainability
  • 🚙 · Functions
  • 🚙 · Variables
  • 🏎️ · When expression
  • 🏎️ · Ranges
  • 🏎️ · Strings & string templates
  • 🏎️ · Nullability ⚙️
  • 🚙 · Literals
  • 🚗 · Function types & literals ⚙️
  • 🏎️ · Inline functions
  • 🏎️ · Tail-recursive functions
  • 🚙 · Variable number of arguments
  • 🚙 · Basic class syntax
  • 🏎️ · Constructors ⚙️
  • 🏎️ · Basics
  • 🏎️ · Accessors
  • 🏎️ · Backing fields
  • 🚗 · Accessors, continued ⚙️
  • 🚙 · Compile-time constants
  • 🏎️ · Lateinit
  • 🚙 · Overriding
  • 🚙 · Interfaces
  • 🚙 · Visibility modifiers
  • 🏎️ · Nested and inner classes
  • 🚗 · Generic variance – motivation
  • 🚗 · Generic variance – fundamental principles
  • 🏎️ · Covariance, Contravariance, Invariance
  • 🏎️ · Star Projections
  • 🏎️ · Data Classes ⚙️
  • 🏎️ · Object Declarations
  • 🏎️ · Object Expressions
  • 🏎️ · Companion Objects ⚙️
  • 🚀 · Delegating interface implementation ⚙️
  • 🚀 · Delegated Properties ⚙️
  • 🚀 · Summary
  • 🚗 · Introduction
  • 🚀 · Safely Emulating Dynamic Dispatch
  • 🚀 · Modeling Illegal States
  • 🚀 · Modeling States and Structure
  • 🚀 · Modeling States and Structure: Considerations
  • 🏎️ · Reified Type Parameters
  • 🏎️ · Infix Functions
  • 🏎️ · Operators
  • 🏎️ · Type Aliases
  • 🚀 · Inline (Value) Classes
  • 🚗 · Functional (SAM) Interfaces
  • 🚀 · Motivation
  • 🚀 · Syntax and Behavior
  • 🚀 · Functions with Receiver
  • 🏎️ · Qualified This ⚙️
  • 🚀 · What Extension Functions Are Not
  • 🚀 · Nullable & Generic Receivers ⚙️
  • 🏎️ · Generic Receivers — continued
  • 🏎️ · Operators as Extensions
  • 🚀 · Introduction
  • 🚀 · also() & apply()
  • 🚀 · also() vs. apply()
  • 🚀 · let() & takeX()
  • 🚀 · with(), run() vs. with()
  • 🚀 · Closing Remarks & Exercises ⚙️
  • 🚀 · What makes a DSL
  • 🚀 · How to make your own ⚙️
  • 🚀 · Returning a Result
  • 🚀 · kotlin.Result
  • 🚀 · Combining and Composing Results
  • 🚀 · Considerations
  • 🚗 · Basic Collections: Introduction
  • 🚗 · Functional vs. (?) Object-Oriented Programming
  • 🚗 · Collection Operations: Overview
  • 🚗 · Transformations
  • 🚗 · Filtering
  • 🚗 · Single-element access
  • 🚗 · Predicates
  • 🚗 · Aggregators
  • 🚗 · Grouping
  • 🚗 · Why we need them
  • 🚗 · How They Work & How To Use Them
  • 🚀 · Yield vs. Return & How Pausing Functions Work
  • 🚗 · Iterable vs. Sequence vs. Java Stream

if else assignment kotlin

A gentle start to Kotlin

© 2022. MIT License.

Conditional Statements - if and when

if else assignment kotlin

So far the programs we have written all turn out pretty much the same. So no matter what the input we got the same output.

Or the shorthand that fits on a line for just assignment.

Note as a block else is optional but when it’s being used as an expression (ex. the quickGrade assignment above) then else has to be there.

Collections and Ranges

With collections we can use in to check if something exists and !in to see if it does not. In the case of maps by default it checks the keys and if you want to check with values use in mapName.values

We can do the same thing with ranges as well.

We use when for dealing with more than 2 branches. This has some very powerful syntax that improves from C-like languages with the switch case syntax.

It works with single values, several values collected, ranges and collections as well as many more complex matchers.

Conditionals - CS199 IKP

Control Flow: if, when, for, while - Official docs

Guide to the “when{}” Block in Kotlin - Baeldung

If-Else Expression in Kotlin - Baeldung

Related Posts

Web services with kotlin using ktor (installation) 31 dec 2020, launch, join, and hundreds of thousands of jobs 01 apr 2020, intro to coroutines 31 mar 2020.

if/then/else

if statements in Kotlin are just like Java, with one exception: they are an expression, so they always return a result.

Basic syntax

A basic Kotlin if statement:

You can also write that statement like this:

The if / else construct:

if/else-if/else

The complete Kotlin if/else-if/else expression looks like this:

if expressions always return a result

The if construct always returns a result, meaning that you can use it as an expression. This means that you can assign its result to a variable:

This means that Kotlin doesn’t require a special ternary operator .

Content created by Alvin Alexander and released under this license .

results matching " "

No results matching " ".

  • Overview and Setup
  • Introduction
  • Variables and Data Types
  • Control Flow
  • Null Safety
  • Function Basics
  • Infix Notation
  • Classes and Objects
  • Getters and Setters
  • Inheritance
  • Abstract Classes
  • Data Classes
  • Type Checks and Smart Casts

Kotlin Control Flow: if and when expressions, for and while loops

Kotlin Control Flow: if and when expressions, for and while loops

In this article, You’ll learn how to use Kotlin’s control flow expressions and statements which includes conditional expressions like if , if-else , when and looping statements like for , while , and do-while .

If Statement

The If statement allows you to specify a section of code that is executed only if a given condition is true-

The curly braces are optional if the body of if statement contains a single line -

If-Else Statement

The if-else statement executes one section of code if the condition is true and the other if the condition is false -

Using If as an Expression

In Kotlin, You can use if as an expression instead of a statement. For example, you can assign the result of an if-else expression to a variable.

Let’s rewrite the if-else example of finding the maximum of two numbers that we saw in the previous section as an expression -

Note that when you’re using if as an expression, it is required to have an else branch, otherwise, the compiler will throw an error.

The if-else branches can also have block bodies. In case of block bodies, the last expression is the value of the block -

Unlike Java, Kotlin doesn’t have a ternary operator because we can easily achieve what ternary operator does, using an if-else expression.

If-Else-If Chain

You can chain multiple if-else-if blocks like this -

In the next section, we’ll learn how to represent if-else-if chain using a when expression to make it more concise.

When Expression

Kotlin’s when expression is the replacement of switch statement from other languages like C, C++, and Java. It is concise and more powerful than switch statements.

Here is how a when expression looks like -

when expression matches the supplied argument with all the branches one by one until a match is found. Once a match is found, it executes the matched branch. If none of the branches match, the else branch is executed.

In the above example, all the branches contain a single statement. But they can also contain multiple statements enclosed in a block -

Using when as an expression

Just like if , when can be used as an expression and we can assign its result to a variable like so -

Combining multiple when branches into one using comma

You can combine multiple branches into one using comma. This is helpful when you need to run a common logic for multiple cases -

Checking whether a given value is in a range or not using in operator

A range is created using the .. operator. For example, you can create a range from 1 to 10 using 1..10 . You’ll learn more about range in a future article.

The in operator allows you to check if a value belongs to a range/collection -

Checking whether a given variable is of certain type or not using is operator

Using when as a replacement for an if-else-if chain

While loop executes a block of code repeatedly as long as a given condition is true -

Here is an example -

In the above example, we increment the value of x by 1 in each iteration. When x reaches 6, the condition evaluates to false and the loop terminates.

do-while loop

The do-while loop is similar to while loop except that it tests the condition at the end of the loop.

Since do-while loop tests the condition at the end of the loop. It is executed at least once -

A for-loop is used to iterate through ranges, arrays, collections, or anything that provides an iterator (You’ll learn about iterator in a future article).

Iterating through a range

Iterating through an array.

Iterating through an array using its indices

Every array in Kotlin has a property called indices which returns a range of valid indices of that array.

You can iterate over the indices of the array and retrieve each array element using its index like so -

Iterating through an array using withIndex()

You can use the withIndex() function on arrays to obtain an iterable of IndexedValue type. This allows you to access both the index and the corresponding array element in each iteration -

The output of this snippet is same as the previous snippet.

Break and Continue

Break out of a loop using the break keyword

Skip to the next iteration of a loop using the continue keyword

That’s all folks! In this article, you learned how to use Kotlin’s conditional expressions like if , if-else , when , and looping statements like for , while and do-while . You can find more articles from the sidebar menu.

Share on social media

Kotlin Tutorial

Kotlin classes, kotlin examples, kotlin if ... else, kotlin conditions and if..else.

Kotlin supports the usual logical conditions from mathematics:

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

You can use these conditions to perform different actions for different decisions.

Kotlin has the following conditionals:

  • Use if to specify a block of code to be executed, if a specified condition is true
  • Use else to specify a block of code to be executed, if the same condition is false
  • Use else if to specify a new condition to test, if the first condition is false
  • Use when to specify many alternative blocks of code to be executed

Note: Unlike Java, if..else can be used as a statement or as an expression (to assign a value to a variable) in Kotlin. See an example at the bottom of the page to better understand it.

Use if to specify a block of code to be executed if a condition is true .

Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.

In the example below, we test two values to find out if 20 is greater than 18. If the condition is true , print some text:

We can also test variables:

Example explained

In the example above we use two variables, x and y , to test whether x is greater than y (using the > operator). As x is 20, and y is 18, and we know that 20 is greater than 18, we print to the screen that "x is greater than y".

Advertisement

Kotlin else

Use else to specify a block of code to be executed if the condition is false .

In the example above, time (20) is greater than 18, so the condition is false , so we move on to the else condition and print to the screen "Good evening". If the time was less than 18, the program would print "Good day".

Kotlin else if

Use else if to specify a new condition if the first condition is false .

In the example above, time (22) is greater than 10, so the first condition is false . The next condition, in the else if statement, is also false , so we move on to the else condition since condition1 and condition2 is both false - and print to the screen "Good evening".

However, if the time was 14, our program would print "Good day."

Kotlin If..Else Expressions

In Kotlin, you can also use if..else statements as expressions (assign a value to a variable and return it):

When using if as an expression, you must also include else (required).

Note: You can ommit the curly braces {} when if has only one statement:

Tip: This example is similar to the "ternary operator" (short hand if...else) in Java.

Get Certified

COLOR PICKER

colorpicker

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Top Tutorials

Top references, top examples, get certified.

  • TutorialKart
  • SAP Tutorials
  • Salesforce Admin
  • Salesforce Developer
  • Visualforce
  • Informatica
  • Kafka Tutorial
  • Spark Tutorial
  • Tomcat Tutorial
  • Python Tkinter

Programming

  • Bash Script
  • Julia Tutorial
  • CouchDB Tutorial
  • MongoDB Tutorial
  • PostgreSQL Tutorial
  • Android Compose
  • Flutter Tutorial
  • Kotlin Android

Web & Server

  • Selenium Java
  • Kotlin Java
  • Kotlin Tutorial
  • Setup Kotlin(Java) Project
  • Kotlin Example Program
  • Convert Java file to Kotlin
  • main() function
  • Kotlin – For Loop
  • Kotlin – While Loop
  • Kotlin – Do-while Loop
  • Kotlin – break
  • Kotlin – continue
  • Kotlin – For i in range
  • Kotlin – Infinite While loop
  • Kotlin Ranges
  • Array Basics
  • Kotlin – Create Array
  • Kotlin – Create Empty Array
  • Kotlin – Create Integer Array
  • Kotlin – Create String Array
  • Kotlin – Create Byte Array
  • Kotlin – Array of Arrays
  • Kotlin – Get Array Size
  • Kotlin – Get Element of Array at Specific Index
  • Kotlin – Set Element of Array at Specific Index
  • Kotlin – Get First Element of Array
  • Kotlin – Get Last Element of Array
  • Kotlin – Print Array in Single Line
  • Array Checks
  • Kotlin – Check if Array is Empty
  • Kotlin – Check if Array Contains Specified Element
  • Array Loops
  • Kotlin – Iterate over Array
  • Kotlin – Array For Loop
  • Kotlin – Array While Loop
  • Array Sorting
  • Kotlin – Array Sorting
  • Kotlin – Sort Array of Integers
  • Kotlin – Sort Array of Strings
  • Kotlin – Sort Array of Strings based on Length
  • Kotlin – Sort Array in Descending Order
  • Kotlin – Classes and Constructors
  • Kotlin – Sealed Class
  • Kotlin – Data Class
  • Kotlin – Enum
  • Kotlin – Extension Functions
  • Inheritance
  • Kotlin – Inheritance
  • Kotlin – Override Method of Super Class
  • Abstraction
  • Kotlin – Abstraction
  • Kotlin – Abstract Class
  • Kotlin – Interfaces
  • Kotlin Try Catch
  • Kotlin – Throw Exception
  • Kotlin – Create custom Exception
  • Kotlin – Initialize string
  • Kotlin – Create empty string
  • Kotlin – Define a string constant
  • Kotlin – Get string length
  • Kotlin – Print a string
  • Kotlin – Concatenate strings
  • Kotlin – Compare strings
  • Kotlin – Multiline strings
  • Kotlin – Check if strings are equal
  • Kotlin – Check if strings are equal ignoring case
  • Kotlin – Check if string is empty
  • Kotlin – Check if string contains specific substring
  • Kotlin – Check if string contains specific character
  • Kotlin – Check if string starts with specific prefix
  • Kotlin – Check if string starts with specific character
  • Kotlin – Check if string ends with specific suffix
  • Kotlin – Check if string ends with specific character
  • Kotlin – Check is string matches regular expression
  • Kotlin – Count number of words in string
  • Kotlin – Find index of substring
  • Kotlin – Get random character from string
  • Kotlin – Substring
  • Transformations
  • Kotlin – Capitalize a string
  • Kotlin – Convert string to lowercase
  • Kotlin – Convert string to uppercase
  • Kotlin – Filter characters of string
  • Kotlin – Join strings by a separator
  • Kotlin – Remove first N characters from string
  • Kotlin – Remove last N haracters from string
  • Kotlin – Repeat string N times
  • Kotlin – Reverse a string
  • Kotlin – Sort characters in string
  • Kotlin – String replace
  • Kotlin – Trim white spaces around string
  • Split Operations
  • Kotlin – Split string
  • Kotlin – Split string to lines
  • Kotlin – Split string by comma
  • Kotlin – Split string by single space
  • Kotlin – Split string by any whitespace character
  • Kotlin – Split string by one or more spaces
  • Conversions
  • Kotlin – Convert char array to string
  • Kotlin – Convert string to char array
  • Kotlin – Convert byte array to string
  • Kotlin – Convert string to byte array
  • Kotlin – Convert string to list of characters
  • Kotlin – Convert list of characters to string
  • Kotlin – Convert string to set of characters
  • Character specific Operations
  • Kotlin – Get character at specific index in string
  • Kotlin – Get first character in string
  • Kotlin – Get last character in string
  • Kotlin – Iterate over each character in string
  • Kotlin – Insert character at specific index in string
  • Kotlin – Get unique characters in string
  • Kotlin – Remove character at specific index in string
  • Kotlin – Remove first character in string
  • Kotlin – Remove last character in string
  • Kotlin – Replace specific character with another in a string
  • Kotlin – Remove specific character in a string
  • String Formatting
  • Kotlin – Write variable inside string
  • String Collections
  • Kotlin – List of strings
  • Kotlin String List – Filter based on Length
  • Kotlin – Filter only strings in this list
  • Kotlin List – Filter non-empty strings
  • Kotlin – Create a set of strings
  • Kotlin – Create string array
  • Kotlin – Sort array of strings
  • Kotlin – Sort string array based on string length
  • Create Operations
  • Kotlin – Create file
  • Kotlin – Create a directory
  • Kotlin – Create directory recursively
  • Get Properties / Meta
  • Kotlin – Get file creation timestamp
  • Kotlin – Get file extension
  • Kotlin – Get file last modified timestamp
  • Kotlin – Get file name
  • Kotlin – Get file size
  • Iterate over files
  • Kotlin – Iterate through all files in a directory
  • File Checks
  • Kotlin – Check if file exists
  • Kotlin – Check if file is readable
  • Kotlin – Check if file is writable
  • Kotlin – Check if directory exists
  • Read Operations
  • Kotlin – Read file
  • Kotlin – Read file as list of lines
  • Kotlin – Read file character by character
  • Kotlin – Read file line by line
  • Kotlin – Read file into a string
  • Write / Update Operations
  • Kotlin – Append to text file
  • Kotlin – Copy content of a file to another file
  • Kotlin – Copy directory
  • Kotlin – Copy file
  • Kotlin – Move file
  • Kotlin – Move directory
  • Kotlin – Rename file
  • Kotlin – Rename directory
  • Kotlin – Replace specific string in file
  • Kotlin – Write to File
  • Delete Operations
  • Kotlin – Delete a file
  • Kotlin – Delete / remove all content in text file
  • Kotlin – Delete a directory
  • Kotlin - Convert List to Set
  • Kotlin - Create an empty list
  • Kotlin - Filter elements of a List based on Condition
  • Kotlin - Filter even numbers in a list
  • Kotlin - Filter List of strings based on length
  • Kotlin - Filter Odd Numbers in a list
  • Kotlin - Filter only integers in a list
  • Kotlin - Filter only non-empty strings of a list
  • Kotlin - Filter only strings from a list
  • Kotlin - Iterate over Elements of List using For Loop in Kotlin?
  • HKotlin - Iterate over List of Lists
  • Kotlin - Remove all occurrences of element in a list
  • Kotlin - Remove all Elements from a List
  • Kotlin - Remove specific Element in list
  • Kotlin - Access index of element in a list while filtering
  • Kotlin - Add element to List at specific index
  • Kotlin - Add Element to List
  • Kotlin - Define a List of Integers
  • Kotlin - Define a List of Lists
  • Kotlin - Define a List of strings
  • Kotlin - Read file content as a list of lines
  • Kotlin - Remove element at specific index in list
  • Kotlin - replace an Element at specific Index
  • Kotlin List forEach – Example
  • Kotlin List.all()
  • Kotlin List.any()
  • Kotlin List.component1()
  • Kotlin List.component2()
  • Kotlin List.component3()
  • Kotlin List.component4()
  • Kotlin List.component5()
  • Kotlin List.contains()
  • Kotlin List.containsAll()
  • Kotlin List.count()
  • Kotlin List.get()
  • Kotlin List.indexOf()
  • Kotlin List.indices Property
  • Kotlin List.isEmpty()
  • Kotlin List.iterator()
  • Kotlin List.lastIndex
  • Kotlin List.lastIndexOf()
  • Kotlin List.size
  • Kotlin List.subList()
  • Kotlin Mutable List
  • Kotlin – Add two numbers
  • Kotlin – Armstrong number
  • Kotlin – Average of two numbers
  • Kotlin – Average of numbers given in array
  • Kotlin – Check if given number is part of Fibonacci series
  • Kotlin – Check prime number
  • Kotlin – Even number
  • Kotlin – Factorial
  • Kotlin – Factors of a number
  • Kotlin – Fibonacci series
  • Kotlin – Find largest of two numbers
  • Kotlin – Find smallest of two numbers
  • Kotlin – Find largest of three numbers
  • Kotlin – Find smallest of three numbers
  • Kotlin – Odd number
  • Kotlin – Palindrome
  • Kotlin – Print prime numbers
  • Kotlin – Product of digits in a number
  • Kotlin – Reverse a number
  • Kotlin – Sum of first n natural numbers
  • Kotlin – Sum of squares of first n natural numbers
  • Kotlin – Sum of digits in a number
  • Kotlin Interview Questions
  • Related Tutorials
  • Kotlin Android Tutorial
  • How to Learn Programming
  • ❯ Kotlin Tutorial

Kotlin If-Else

Kotlin if else.

Kotlin If Else is a decision making statement, that can be used to execute one of the two code blocks based on the result of a condition.

In this tutorial, you can learn the syntax of if-else statement, and understand how to write if-else statements in a Kotlin program with examples.

The syntax of if else statement in Kotlin is as shown in the following.

  • if , else : Kotlin keywords.
  • condition : a boolean expression or something that evaluates to a boolean value.
  • () encloses condition, and {} encloses code blocks.

If the condition evaluates to true, runtime executes corresponding if-block statement(s) .

If the condition evaluates to false, runtime executes corresponding else-block statement(s) .

else block is optional. So, if-else without else would become a simple if statement in Kotlin .

1. Check if number is even or odd using if-else

In the following program, we check if the given number is even number or odd number using an if-else statement, and print the output.

Since a=13 is odd,  a%2==0 evaluates to false. So, the else block is executed.

2. If-else optional braces

Braces are optional if the number of statements in the corresponding block is one.

In the following example, we have only one statement in if and else blocks. So, the braces are optional for both the if and else blocks. Hence no braces.

Though braces are optional, it is recommended to use braces to enclose if or else code blocks to enhance the readability of the program.

Nested If Else

We can nest an if-else statement inside another if-else statement. When we say if-else in this context, it could be simple if statement, or if-else statement or if-else-if statement.

In the following example, we have written an if-else-if statement inside a simple if statement.

Run the program.

if-else-if statement inside if statement is like any other Kotlin statement. So, the if the execution enters inside the if statement, if-else-if shall be executed like we have seen in the previous examples.

Concluding this Kotlin Tutorial , we learned what if-else statement is and its variations in Kotlin programming language.

Popular Courses by TutorialKart

App developement, web development, online tools.

logo

Jonas Rodehorst

Kotlin If-Else on one line short (with Examples)

Kotlin If-Else on one line short (with Examples) 🩳

In Kotlin, you can have if-else statements on one line. To write an if-else statement on one line, follow the conditional expression syntax:

For example:

Output in the console:

This is useful with shorter if-else statements because they allow you to write fewer lines of code while maintaining readability. However, avoid turning longer if-else statements into one-liners. Doing so can cause your code to lose clarity.

Four ways of If-Else Statements in Kotlin

To summarize the different methods of the if-else statement, here are three different variants of the same if-else query.

Methode 1 - The normal if else

Methode 2 - without curly brackets, methode 3 - one-liner, methode 4 - when statement.

All these methods achieve the same goal in different ways. Which of these methods you should use depends very much on the application and can therefore not be said so sweepingly.

Special case null check

If you have a nullable reference and you want to use that reference you have to check if the reference is not null. To do that you could so it in a one-line if else check, like so:

Instead of writing the complete if expression, you can also express this with the Elvis operator ?:

If the expression to the left of ?: is not null, the Elvis operator returns it, otherwise it returns the expression to the right. Note that the expression on the right-hand side is evaluated only if the left-hand side is null.

Thanks for reading. Happy coding!

MarketSplash

Kotlin Let Else: How To Implement And Apply It

"Kotlin let else" provides a streamlined approach to handle specific code scenarios. Explore its mechanics, benefits, and best practices to enhance your coding prowess in Kotlin.

💡 KEY INSIGHTS

  • The Kotlin 'let' function is essential for handling nullable objects, eliminating the need for explicit null checks and simplifying code.
  • Combining 'let' with the Elvis operator allows dual-path execution, providing clarity and efficiency in handling nullable and non-nullable scenarios.
  • Practical use cases for 'let' include handling null safety, transforming data, and filtering lists, showcasing its versatility in different coding contexts.
  • The article emphasizes avoiding common mistakes, such as overusing 'let' or confusing it with other scoping functions, ensuring code readability and maintainability.

In the evolving world of Kotlin , the " let else " construct is gaining traction among developers. This feature offers a clean and concise way to handle certain situations in code.

if else assignment kotlin

Understanding The Basics Of Kotlin's Let

Practical use cases of let, introduction to let else in kotlin, working examples of let else, common mistakes and how to avoid them, frequently asked questions, basic syntax of let, use cases for let, chaining operations, avoiding shadowing.

In the Kotlin language, let is a scoping function that is part of the standard library. It allows you to invoke one or more functions on an object and then return the result.

This function is particularly useful for performing operations on nullable objects without the need to explicitly check for null values.

The most straightforward way to use let is by invoking it on an object. The object then becomes the lambda argument, usually represented by the default name it .

One of the primary use cases for let is to handle nullable values . By using the safe call operator ?. with let , you can ensure that the code block inside the lambda is only executed if the object is non-null.

Another common scenario is to transform an object and return a new value.

Kotlin's let allows for chaining operations, providing a cleaner way to perform multiple operations on a single object.

When working with nested scoping functions , it's essential to be cautious about variable shadowing. Instead of using the default it , you can provide a custom name for the lambda argument.

Handling Null Safety

Transformations, filtering lists, avoiding temporary variables, combining multiple let blocks, using with resources.

One of the primary advantages of Kotlin's let function is its ability to seamlessly handle nullable types. This eliminates the need for verbose null checks in your code.

Another strength of let is its ability to transform data. You can take an object, process it, and return a new form of that object within the same block.

When working with collections, let becomes a handy tool to filter and process lists.

In many situations, developers create temporary variables to hold intermediate results. With let , you can reduce the need for these variables.

For more complex operations , you can combine multiple let blocks . This can help in breaking down operations into smaller, more readable chunks.

In some scenarios, you might need to work with resources that require closure, like streams or files. Let can be beneficial here.

What Is Let Else?

How does it work, benefits of using let else, common scenarios.

However, Kotlin doesn't have a built-in let else construct . Instead, developers often combine the use of let with the Elvis operator ?: to achieve similar functionality.

The combination of let and the Elvis operator ?: allows for a dual-path execution. If the object on which let is called is non-null, the lambda within let is executed.

If it's null, the code after the Elvis operator is executed.

Using this pattern provides a concise way to handle nullable objects. It aids in writing cleaner code by reducing the need for verbose null checks, making the code more readable and maintainable.

There are many instances where this combination can be useful :

  • Fetching and processing data that might be null.
  • Handling user input which might not always be available.
  • Working with databases or APIs where the return value might be nullable.

User Authentication

Configurations and settings, processing data streams, handling api responses, database interactions, user input validation.

In applications, verifying the authenticity of a user is crucial. Using let else , you can gracefully handle situations where user details might be missing.

In applications, settings or configuration data might not always be available. Here's how you can use let else to provide default values.

When dealing with data streams, not every packet might be valid. The let else pattern can help in handling such scenarios.

APIs do not always return the expected data. Let else can be a lifesaver in gracefully managing these unpredictable scenarios.

Database queries might sometimes return null values, especially when looking for specific records. Here's how let else can be applied.

When developing applications, user input is not always guaranteed. The let else pattern can be used to ensure that only valid input is processed.

Overusing Let Else

Confusing let with other scoping functions, ignoring return values, nested let blocks, misusing the elvis operator, overlooking side effects.

Coding with Kotlin's 'let else' is like dancing with precision; every step is deliberate, every move null-safe, ensuring a graceful execution without missteps.

macOS Developer

Source: Stack Overflow

A frequent mistake is overusing the let else pattern , making the code cluttered. While it's a powerful tool, it's essential to remember that not every situation requires its use.

Consider other control structures when they make more sense.

Kotlin offers several scoping functions like also , run , and apply . Mixing them up can lead to unexpected results.

Ensure you understand each function's purpose and apply them correctly.

The let function will always return a result. Ignoring this result can lead to missed opportunities in chaining or capturing transformations.

While it's possible to nest let blocks , doing so excessively can make your code hard to read. It's often better to split complex operations into multiple functions or use other scoping functions.

The Elvis operator ?: is central to the let else pattern . However, using it without fully understanding can lead to bugs. Always ensure the right side of the Elvis operator handles the null scenario correctly.

Remember that the let block can have side effects. If multiple operations are being performed inside it, ensure they don't interfere with each other or produce unexpected results.

What's the primary purpose of the let function in Kotlin?

The let function is primarily used as a scoping function, allowing you to invoke one or more functions on an object and then return a result. It's especially handy with nullable types, helping to avoid null pointer exceptions.

How does let differ from other Kotlin scoping functions?

Kotlin provides several scoping functions like also , run , apply , and with . The main distinction of let is that it provides access to the object it's invoked upon as a lambda argument and allows you to return a result.

Why would I use the let-Elvis combination?

The combination of let with the Elvis operator ?: (often referred to as let else) provides a concise way to handle nullable objects. If the object is non-null, the let block is executed; otherwise, the code after the Elvis operator is run.

Can I use let for non-nullable types?

Absolutely. While let shines with nullable types, it can be used with non-nullable objects as well. In such cases, it acts as a transformation or scoping function.

How do I avoid overusing the let function?

It's crucial to understand the specific use cases where let adds value. While it's a powerful tool, not every situation demands its application. Regularly reviewing your code and understanding other Kotlin constructs can help in making the right choice.

Let's see what you learned!

Which combination best describes the use of let with the Elvis operator for handling nullable objects in Kotlin?

Continue learning with these kotlin guides.

  • Kotlin Abstract Class And Its Practical Application
  • Kotlin Add To List: How To Implement And Use Effectively
  • Kotlin Filter Function And Its Practical Applications
  • Kotlin Varargs: How To Use Them Effectively
  • Kotlin Set: Efficient Ways To Utilize Its Features

Subscribe to our newsletter

Subscribe to be notified of new content on marketsplash..

COMMENTS

  1. Kotlin Ternary Conditional Operator

    Also in addition to the fact that if in Kotlin is not a statement but an expression (i.e. it evaluates to a value), in the case where you have multiple statements inside the body of an if branch (or the body of else or else if), the last line of the block is the value of that branch. For example:

  2. If-Else Expression in Kotlin

    3. Kotlin If-Else Expression. An expression is a combination of one or more values, variables, operators, and functions that execute to produce another value. val number: Int = 25. val result: Int = 50 + number. Copy. Here, 50 + number is an expression that returns an integer value.

  3. Conditions and loops

    Its simple form looks like this. when (x) { 1 -> print("x == 1") 2 -> print("x == 2") else -> { print("x is neither 1 nor 2") } } when matches its argument against all branches sequentially until some branch condition is satisfied. when can be used either as an expression or as a statement. If it is used as an expression, the value of the first ...

  4. Write conditionals in Kotlin

    In Kotlin, branching can be achieved with if/else or when conditionals. The body of an if branch in an if/else conditional is only executed when the boolean expression inside the if branch condition returns a true value. Subsequent else if branches in an if/else conditional get executed only when previous if or else if branches return false values.

  5. Kotlin Ternary Conditional Operator

    Unlike other languages, if and when in Kotlin are expressions. The result of such an expression can be assigned to a variable. Using this fact, both if and when can be substituted for the ternary operator in their own way. 2.1. Using if-else

  6. Kotlin if...else Expression (With Examples)

    Kotlin Introduction. Kotlin Hello World; Kotlin Data Types; Kotlin Operators; Kotlin Type Conversion; Kotlin Expression & Statement; Kotlin Comments; Kotlin Input/Output

  7. Kotlin if-else expression

    There are different types of if-else expressions in Kotlin: if expression. if-else expression. if-else-if ladder expression. nested if expression. if statement: It is used to specify whether a block of statements will be executed or not, i.e. if a condition is true, then only the statement or block of statements will be executed otherwise it ...

  8. Conditional statements in Kotlin: if expressions and when constructs

    In programming, conditional statements are constructs that make it possible to control a program flow based on conditions. The condition can, for example, refer to a specific variable or the state of a program. If the condition is met, the code within the conditional statement is executed. Otherwise the code is skipped or an alternative code block is executed. There are two types of ...

  9. · If expression

    Read on to find out how if/else acts as a replacement for the ternary operator in Kotlin. There is no ternary operator (i.e. <condition> ? <then> : <else> ) in Kotlin. Instead, if/else may be used as an expression:

  10. Kotlin

    When Statement. The when statement is an alternative to if else-if.On every branch of the when statement, a predicate and a body is specified. The body will be executed only for the first predicate that returns true.So it works just like if else-if, but it's preferred because its syntax is better suited for multiple conditions.And thanks to the fact that it's a single statement, Kotlin can ...

  11. Conditional Statements

    Note as a block else is optional but when it's being used as an expression (ex. the quickGrade assignment above) then else has to be there.. Collections and Ranges. With collections we can use in to check if something exists and !in to see if it does not. In the case of maps by default it checks the keys and if you want to check with values use in mapName.values

  12. A New Way to Write Conditional Statements in Kotlin

    In Kotlin, we can replace switch case and if / else with when in a similar way in order to maintain consistency when implementing conditional execution. First, let's see how to implement the example above with the switch in a traditional way: switch case example. Switch case can be replaced with the when statement similarly to if / else.

  13. Kotlin

    This is not always possible, because smart casting cannot be performed if there is a chance that another thread modifies the value between the null check in the assignment. This happens for instance if your x is a nullable var property on the class. In that case, you have this option: x?.let { foo = it }

  14. if/then/else · Kotlin Quick Reference

    This page demonstrates Kotlin's if/then/else construct, including several examples you can try in the REPL. Introduction Preface Getting started Kotlin features Hello, world Hello, world (version 2) The REPL Two types of variables ...

  15. Kotlin Control Flow: if and when expressions, for and while loops

    In Kotlin, You can use if as an expression instead of a statement. For example, you can assign the result of an if-else expression to a variable. Let's rewrite the if-else example of finding the maximum of two numbers that we saw in the previous section as an expression -

  16. Kotlin If ... Else Expressions

    Use else if to specify a new condition to test, if the first condition is false. Use when to specify many alternative blocks of code to be executed. Note: Unlike Java, if..else can be used as a statement or as an expression (to assign a value to a variable) in Kotlin. See an example at the bottom of the page to better understand it.

  17. Kotlin if, else, else if, when (Kotlin Conditional Statements)

    The inline if-else expression is a convenient way to simplify conditional assignments and expressions in Kotlin, making your code more concise and readable. Kotlin if else one line In Kotlin, you can use the ternary conditional operator (also known as the Elvis operator ) to write a one-liner if-else expression.

  18. Kotlin If, If-Else, If-Else-If, Nested If-Else

    Kotlin If Else is a decision making statement, that can be used to execute or not execute a block of statements based on the boolean result of a condition. There are different forms for If-Else statement in Kotlin: if statement, if-else statement, if-else-if statement and finally nested if-else statement.

  19. Multiple Conditions for If-Else statement in Kotlin

    kotlin if else statement. 1. Kotlin: redundant if statement. 3. Kotlin - same condition: multiple if statements or one if statement. 2. How to make this complex if-else statement maintainable in Kotlin. 3. how to change nested if-else to when statements using Kotlin? 0. If - Else in Kotlin. 0.

  20. Kotlin If-Else on one line short (with Examples)

    However, avoid turning longer if-else statements into one-liners. Doing so can cause your code to lose clarity. Four ways of If-Else Statements in Kotlin. To summarize the different methods of the if-else statement, here are three different variants of the same if-else query. Methode 1 - The normal if else

  21. Can Kotlin declare variable in if statement?

    Kotlin "return" statement for when variable assignment. 0. If - Else in Kotlin. 7. Is it possible to declare a variable inside of the "if" condition in Kotlin? 2. kotlin and declaring variables correctly. 0. Kotlin android if statement. Hot Network Questions Estimating Exponents

  22. Kotlin Switch: How To Implement And Use It

    The kotlin switch, known as the `when` construct in Kotlin, streamlines conditional statements in your code. It's more concise and expressive, improving code readability and efficiency. ... String { return when (number) { 1 -> "One" 2 -> "Two" else -> "Unknown number" } } Kotlin's when expression provides a robust and flexible way to handle ...

  23. Kotlin Let Else: How To Implement And Apply It

    The Kotlin 'let' function is essential for handling nullable objects, eliminating the need for explicit null checks and simplifying code. Combining 'let' with the Elvis operator allows dual-path execution, providing clarity and efficiency in handling nullable and non-nullable scenarios. Practical use cases for 'let' include handling null safety ...

  24. Is it possible to declare a variable inside of the "if" condition in

    Kotlin: replace 'cascade if' with 'when' comparing with other variables. 1. Android kotlin - declare a val within if else condition. 1. Kotlin: redundant if statement. 1. Redundant 'if' statement less. 0. If - Else in Kotlin. 1. Replacing "If" with "When" in Kotlin. 3.

  25. Android kotlin

    Kotlin's if-else expressions are also statements, meaning you can set variables with them. Share. Improve this answer. Follow answered Sep 21, 2018 at 19:31. TheWanderer TheWanderer. 17.2k 6 6 gold badges 51 51 silver badges 64 64 bronze badges. 0. Add a comment | 4