Back to Blog

Kotlin: Create a function to test which number is larger

Sandy LaneSandy Lane

Video: Kotlin: Create a function to test which number is larger by Taught by Celeste AI - AI Coding Coach

Watch full page →

Kotlin: Create a Function to Test Which Number Is Larger

In Kotlin, you can easily create a function to compare two numbers and determine which one is larger. This is useful for making decisions in your code based on numeric values. Here, we'll define a simple function that takes two integers and returns the larger of the two.

Code

fun maxOfTwo(a: Int, b: Int): Int {
  // Compare the two numbers and return the larger one
  return if (a > b) a else b
}

// Example usage:
fun main() {
  val num1 = 10
  val num2 = 20
  val larger = maxOfTwo(num1, num2)
  println("The larger number between $num1 and $num2 is $larger")
}

Key Points

  • Define functions in Kotlin using the `fun` keyword followed by the function name and parameters.
  • Use an `if` expression to compare two values and return the larger one.
  • Kotlin's `if` can be used as an expression that returns a value directly.
  • Functions can be called with arguments, and their return value can be stored or printed.