Labs ICT
โญ Pro Login

If & Else

1 min read | Kotlin Tutorial
โญ

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

Life is full of decisions, and your code should be too. Kotlin's if/else works just like most languages, but with a cool twist โ€” it can return a value.

The basic if statement

Use if to run code only when a condition is true.


fun main() {
  val age = 18
  if (age >= 18) {
    println("You can vote!")
  }
}
    

if...else

Add an else branch to handle the case when the condition is false.


fun main() {
  val age = 16
  if (age >= 18) {
    println("You can vote!")
  } else {
    println("Too young to vote.")
  }
}
    

else if chains

Check multiple conditions by chaining else if.


fun main() {
  val score = 85
  if (score >= 90) {
    println("A")
  } else if (score >= 80) {
    println("B")
  } else if (score >= 70) {
    println("C")
  } else {
    println("F")
  }
}
    

if as an expression

Here's the Kotlin special โ€” if can return a value. No ternary operator needed.


fun main() {
  val age = 20
  val result = if (age >= 18) "Adult" else "Minor"
  println(result)
}
    

The last expression in each branch becomes the return value. Clean and readable.

๐Ÿงช Quick Quiz

In Kotlin, can if be used as an expression?