Kotlin. Conditional expression

Conditional expression. Concepts. Features of use with the if and when statements. Examples


Contents


Search other resources:

1. Conditional expression. Concept. Using the if statement in a conditional expression

The Kotlin language allows the use of so-called conditional expressions. In a conditional expression, the if statement (all its types) is bound to some variable (name). Then, by the name of this variable, you can call the code of the conditional expression. Using conditional expressions simplifies your code.

For different kinds of if statements, the syntax for declaring a conditional expression changes accordingly. The Kotlin language prohibits the use of a conditional expression for the shorthand form of the if statement. It is allowed to use a conditional expression only for the full form and the ladder (cascade) form of the if statement.

 

2. Conditional expression syntax for full form: if-else

For the full form of the if-else statement, the syntax of the conditional expression is as follows:

val cond_expr : Type =
  if (condition)
    statements1
  else
    statements2

here

  • cond_expr – the name of the variable that receives the conditional expression;
  • condition – a logical expression;
  • statements1, statements2 – one or more operators enclosed in curly braces.

It is also allowed to use the var modifier in a conditional expression declaration.

 

3. The syntax of the conditional expression for the ladder (cascading) form if-else-if

Conditional expressions can be used for the ladder (cascade) form of the if-else-if statement. In this case, the syntax for declaring a conditional expression is as follows:

val cond_expr =
  if (condition1)
    statements_1
  else
  if (condition2)
    statements_2
  else
    ...
  else
  if (conditionN)
    statements_N
  else
    statements_N+1

where

  • cond_expr – the name of the variable that receives the conditional expression;
  • condition1, condition2, conditionN – logical expressions;
  • statements_1, statements_2, statements_N – one or more operators or values.

 

4. Examples of conditional expressions for the if-else operator
4.1. Minimum between two numbers

Task. Form a conditional expression that gets the minimum value between two real numbers.

Solution.

 

fun main(args:Array<String>) {

  // Conditional expression. Full form: if-else
  // Calculate minimum between two numbers

  // 1. Declaring variables
  val a : Double
  val b : Double

  // 2. Input a, b
  print("a = ")
  a = readLine().toString().toDouble()
  print("b = ")
  b = readLine().toString().toDouble()

  // 3. Form a conditional expression
  val Min =
    if (a<b) a
    else b

  // 4. Call the conditional expression
  println("Min = " + Min)
}

Test example

a = 23
b = 33
Min = 23.0

 

4.2. The absolute value of a number

Task. Form a conditional expression that outputs the modulus of this number for the specified number a.

Solution.

fun main(args:Array<String>) {

  // Conditional expression. Full form: if-else
  // Display the modulus of a number

  // 1. Declaring variables
  val a : Double

  // 2. Input a
  print("a = ")
  a = readLine().toString().toDouble()

  // 3. Form a conditional expression that outputs the modulus of a number
  val PrintAbs =
    if (a<0) println("abs(a) = " + (-a))
    else println("abs(a) = " + a)
}

Test example

a = -37
abs(a) = 37.0

 

5. Examples of conditional expressions for if-else-if statements
5.1. Conditional expression – maximum between three numbers

The example creates a conditional expression named Max that defines a maximum among three numbers a, b, c entered from the keyboard.

fun main(args:Array<String>) {

  // Conditional expression. Cascade form: if-else-if
  // Calculate the maximum between three numbers
  var a : Int
  var b : Int
  var c : Int

  print("a = ")
  a = readLine().toString().toInt()
  print("b = ")
  b = readLine().toString().toInt()
  print("c = ")
  c = readLine().toString().toInt()

  // Conditional expression declaration - calculates the maximum between a, b, c
  // One of the values a, b, c is written to the Max variable
  var Max =
    if ((a>=b)&&(a>=c)) a
    else
    if ((b>=a)&&(b>=c)) b
    else c

  // Call the conditional expression Max
  println("Max = " + Max)
}

Test example

a = 25
b = 30
c = 14
Max = 30

 

5.2. Calculating the characteristics of geometric shapes

Task. Given a radius r and a number n, which determine the number of the figure. Depending on the values of r and n, calculate:

  • circumference, if n = 1;
  • area of a circle, if n = 2;
  • the volume of the sphere, if n = 3.

Solution.

const val Pi = 3.1415

fun main(args:Array<String>) {

  // Conditional expression. Cascade form: if-else-if
  // Calculate the characteristics of a figure

  // 1. Declaring variables
  val r : Double
  val n : Int

  // 2. Input n, r
  print("n = ")
  n = readLine().toString().toInt()
  print("r = ")
  r = readLine().toString().toDouble()

  // 3. Checking if the data is entered correctly
  if ((n<1)||(n>3)||(r<0)) {
    println("Incorrect input.")
    return
  }

  // 4. Declare a conditional expression
  val result : Double =
    if (n==1)
      2*Pi*r
    else
    if (n==2)
      Pi*r*r
    else
    if (n==3)
      4.0/3.0*Pi*r*r*r
    else
      0.0

    // 5. Call the conditional expression
    println("result = " + result)
}

Test example

n = 3
r = 2.5
result = 65.44791666666666

 

6. Using a conditional expression in conjunction with the when operator

A conditional expression can be used in conjunction with the when operator. In simplified form, the syntax for declaring such an expression is as follows

val cond_expr = when {
  ...
}

 

7. Examples of using a conditional expression with the when operator
7.1. Display the name of the day by day number

Task. An integer specifying the day of the week (1..7) is specified. By the entered number, display the name of the corresponding day of the week. Assume that 1 is Monday.

fun main(args:Array<String>) {

  // Conditional expression. The when operator
  // Calculate the name of the day of the week by its number

  // 1. Declaring variables
  val day : Int

  // 2. Input the day
  print("day = ")
  day = readLine().toString().toInt()

  // 3. Declare a conditional expression
  val dayOfWeek : String =
    when (day) {
      1 -> "Monday"
      2 -> "Tuesday"
      3 -> "Wednesday"
      4 -> "Thirsday"
      5 -> "Friday"
      6 -> "Saturday"
      7 -> "Sunday"
      else -> "Incorrect input"
  }

  // 4. Use the conditional expression
  println("dayOfWeek = " + dayOfWeek)
}

Test example

day = 4
dayOfWeek = Thirsday

 

7.2. Number of days in a month

Task. Generate a conditional expression that displays the number of days in this month by the specified month number. When forming an expression, use the when operator. Take into account that not leap-year.

Solution.

fun main(args:Array<String>) {
  // Conditional expression. The when operator
  // Form the number of days in a month

  // 1. Declare variables
  val n : Int

  // 2. Input n
  print("n = ")
  n = readLine().toString().toInt()

  // 3. Form a conditional expression
  val nDays =
    when (n) {
      4, 6, 9, 11 -> 30
      2 -> 28
    else -> 31
  }

  // 4. Display the result
  println("days = " + nDays)
}

Test example

n = 7
days = 31

 


Related topics