Back to Blog

Kotlin with copilot: Use lambda function to print out a name

Sandy LaneSandy Lane

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

Watch full page →

Kotlin with Copilot: Use Lambda Function to Print Out a Name

In Kotlin, lambda functions provide a concise way to define and pass around blocks of code. This example demonstrates how to create a simple lambda that prints a name, showcasing Kotlin's expressive syntax and functional programming capabilities.

Code

fun main() {
  // Define a lambda function that takes a String and prints it
  val printName: (String) -> Unit = { name ->
    println("Name: $name")
  }

  // Call the lambda with a sample name
  printName("Alice")
}

Key Points

  • Lambdas in Kotlin are anonymous functions that can be assigned to variables.
  • The syntax `(String) -> Unit` specifies a function that takes a String and returns nothing.
  • Use curly braces `{}` to define the lambda body, with parameters before the `->` symbol.
  • Lambdas can be called just like regular functions by passing the required arguments.
  • This approach enables clean, reusable, and concise code for simple operations like printing.