Kotlin with Copilot: Create a lambda function to square a number
Video: Kotlin with Copilot: Create a lambda function to square a number by Taught by Celeste AI - AI Coding Coach
Watch full page →Kotlin with Copilot: Create a lambda function to square a number
In Kotlin, lambda functions provide a concise way to define small functions inline. This example demonstrates how to create a simple lambda that takes an integer and returns its square, showcasing Kotlin’s expressive syntax for functional programming.
Code
fun main() {
// Define a lambda function that squares an integer
val square: (Int) -> Int = { number -> number * number }
// Use the lambda function with some sample inputs
println(square(5)) // Output: 25
println(square(10)) // Output: 100
}
Key Points
- Kotlin lambda syntax uses curly braces with input parameters followed by an arrow and the expression.
- Lambda functions can be assigned to variables with explicit types for clarity and reusability.
- Calling a lambda is done like a regular function using parentheses and passing arguments.
- Lambdas enable concise, inline function definitions without needing full function declarations.