Back to Blog

Kotlin with Copilot: Create a lambda function to add 2 numbers

Sandy LaneSandy Lane

Video: Kotlin with Copilot: Create a lambda function to add 2 numbers by Taught by Celeste AI - AI Coding Coach

Watch full page →

Kotlin with Copilot: Create a lambda function to add 2 numbers

In Kotlin, lambda functions provide a concise way to define small blocks of code that can be passed around and executed. This example demonstrates how to create a simple lambda function that takes two integers and returns their sum, showcasing Kotlin's clean syntax for functional programming.

Code

fun main() {
  // Define a lambda function that takes two Int parameters and returns their sum
  val add: (Int, Int) -> Int = { a, b -> a + b }

  // Use the lambda function
  val result = add(5, 7)

  // Print the result
  println("Sum of 5 and 7 is $result")
}

Key Points

  • Kotlin lambda functions can be assigned to variables with explicit type declarations.
  • The lambda syntax uses curly braces with parameters followed by the function body separated by an arrow.
  • Lambdas can be invoked just like regular functions using the variable name and parentheses.
  • This approach enables concise and reusable code for simple operations like addition.