Back to Blog

Kotlin with copilot: Use lambda function to print the full name

Sandy LaneSandy Lane

Video: Kotlin with copilot: Use lambda function to print the full name by Taught by Celeste AI - AI Coding Coach

Watch full page →

Kotlin with Copilot: Use Lambda Function to Print the Full Name

In Kotlin, lambda functions provide a concise way to represent small blocks of code that can be passed around and executed. This example demonstrates how to create a lambda function that takes first and last names as input and prints the full name.

Code

fun main() {
  // Define a lambda that takes two strings and prints the full name
  val printFullName: (String, String) -> Unit = { firstName, lastName ->
    println("Full name: $firstName $lastName")
  }

  // Call the lambda with sample names
  printFullName("John", "Doe")
}

Key Points

  • Kotlin lambdas are anonymous functions that can be stored in variables and passed as parameters.
  • The lambda syntax uses curly braces and the '->' symbol to separate parameters from the function body.
  • In this example, the lambda takes two strings and prints them formatted as a full name.
  • Lambdas can simplify code by avoiding the need for full function declarations when only small snippets of code are needed.