Back to Blog

Kotlin with Copilot: Create a one line lambda function

Sandy LaneSandy Lane

Video: Kotlin with Copilot: Create a one line lambda function by Taught by Celeste AI - AI Coding Coach

Watch full page →

Kotlin with Copilot: Create a One-Line Lambda Function

In Kotlin, lambda functions provide a concise way to represent anonymous functions. This example demonstrates how to create a simple one-line lambda function to perform an operation, such as doubling a number, making your code more readable and expressive.

Code

// Define a one-line lambda function that doubles an integer
val double: (Int) -> Int = { number -> number * 2 }

// Use the lambda function
fun main() {
  val result = double(5)
  println("Double of 5 is $result")  // Output: Double of 5 is 10
}

Key Points

  • Kotlin lambda syntax uses curly braces with parameters followed by the function body.
  • One-line lambdas can omit the return keyword; the expression's value is returned implicitly.
  • Lambda types are declared with parameter types and return type, e.g., (Int) -> Int.
  • Lambdas enable concise and functional-style programming in Kotlin.