Conditional Statement

Conditional Statement


  • In Kotlin conditional statements are same as C / C++.

There are different types of if-else expressions in Kotlin:

  • if expression
  • if-else expression
  • if-else-if ladder expression
  • nested 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.
 
  1. If Statement:
fun main() { val a = 2 val b = 3 // if condition var max = a if (a < b){ max = b } println("max is $max") }
 
  1. if - else Statement:
fun main(){ val a = 2 val b = 3 // With else if (a > b) { max = a } else { max = b } println("max is $max") }
 
  1. if - else if - else Statements:
import java.util.Scanner fun main(args: Array<String>) { // create an object for scanner class val reader = Scanner(System.`in`) print("Enter any number: ") // read the next Integer value var num = reader.nextInt() var result = if ( num > 0){ "$num is positive number" } else if( num < 0){ "$num is negative number" } else{ "$num is equal to zero" } println(result) }
 
  1. Nested if Statement:
import java.util.Scanner fun main(args: Array<String>) { // create an object for scanner class val reader = Scanner(System.`in`) print("Enter three numbers: ") var num1 = reader.nextInt() var num2 = reader.nextInt() var num3 = reader.nextInt() var max = if ( num1 > num2) { if (num1 > num3) { "$num1 is the largest number" } else { "$num3 is the largest number" } } else if( num2 > num3){ "$num2 is the largest number" } else{ "$num3 is the largest number" } println(max) }
 
  1. As Expression:
fun main() { val a = 2 val b = 3 // As expression max = if (a > b) a else b // You can also use `else if` in expressions: val maxLimit = 1 val maxOrLimit = if (maxLimit > a) maxLimit else if (a > b) a else b println("max is $max") println("maxOrLimit is $maxOrLimit") }