Skip to main content

If Expression in Kotlin

1 min read Updated June 30, 2026
Share:
On this page (7sections)

If Expression Definition

  • In Kotlin, if is an expression, it returns a value based on condition.
  • Which is equivalent to the ternary operator for other languages. In Kotlin there is no ternary operator (condition ? then: else).

Syntax

// As expression 
val varibale = if (condition) value1 else value1

For example,

val maximum = if(num1>num1) num1 else num2

If expression Example Program

// If Expression Kotlin example program
// Conditional Statements Kotlin Programs, Basic Kotlin Programs

fun main(args: Array<String>) {

    var num1 = 5
    var num2 = 10
    
    //If Expression returns Maximum Value
    val maximum = if(num1>num1) num1 else num2
    
    println("Maximum Value : $maximum")
}

Sample Output

Maximum Value : 10

How It Works

Here is a step-by-step walkthrough of how the Kotlin program for If Expression in Kotlin runs, line by line:

  1. fun main(args: Array<String>) { — defines a function used by the program.
  2. var num1 = 5 — declares or assigns a value the program uses.
  3. var num2 = 10 — declares or assigns a value the program uses.
  4. val maximum = if(num1>num1) num1 else num2 — declares or assigns a value the program uses.
  5. println("Maximum Value : $maximum") — writes a line of output shown in the sample output.

After running it, compare your console output with the Sample Output above. Try changing the values and re-running the program to see how the result changes — experimenting is the fastest way to understand the logic.

Frequently Asked Questions

What is If Expression in Kotlin?
If Expression is demonstrated in this Kotlin tutorial with a complete, runnable example and its sample output.
How do I run this Kotlin example?
Run it in IntelliJ IDEA or Android Studio, or compile from the command line with `kotlinc file.kt -include-runtime -d file.jar` and run `java -jar file.jar`.
How can I practice If Expression?
Copy the example into IntelliJ IDEA or Android Studio, run it, then change the values or add print statements to see how the output changes.

Related Tutorials

Search tutorials