Kotlin with Coilot: Create a list of 10 numbers and use lambda function to find the even numbers
Video: Kotlin with Coilot: Create a list of 10 numbers and use lambda function to find the even numbers by Taught by Celeste AI - AI Coding Coach
Watch full page →Kotlin with CoPilot: Create a List of 10 Numbers and Use Lambda to Find Even Numbers
In this example, we create a list of 10 integers in Kotlin and use a lambda function with the `filter` method to extract all even numbers from the list. This demonstrates how Kotlin’s concise syntax and higher-order functions make working with collections straightforward and expressive.
Code
fun main() {
// Create a list of numbers from 1 to 10
val numbers = (1..10).toList()
// Use a lambda function to filter even numbers
val evenNumbers = numbers.filter { it % 2 == 0 }
// Print the list of even numbers
println("Even numbers: $evenNumbers")
}
Key Points
- Kotlin's range operator `(1..10)` creates a sequence of numbers easily converted to a list.
- The `filter` function takes a lambda to select elements matching a condition—in this case, even numbers.
- The lambda expression `it % 2 == 0` checks if a number is divisible by 2 without a remainder.
- Kotlin's concise syntax allows writing collection operations in a readable and functional style.