Copilot with Kotlin: Create a new divisible by 3 list
Video: Copilot with Kotlin: Create a new divisible by 3 list by Taught by Celeste AI - AI Coding Coach
Watch full page →Copilot with Kotlin: Create a New Divisible by 3 List
In Kotlin, filtering a list to create a new one containing only elements divisible by 3 is straightforward and expressive. Using Kotlin's powerful collection functions, you can easily generate a filtered list with concise and readable code.
Code
fun main() {
val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12)
// Filter the list to include only numbers divisible by 3
val divisibleByThree = numbers.filter { it % 3 == 0 }
println(divisibleByThree) // Output: [3, 6, 9, 12]
}
Key Points
- Kotlin's
filterfunction creates a new list by selecting elements that satisfy a condition. - The lambda expression
{ it % 3 == 0 }checks divisibility by 3 for each element. - Original lists remain unchanged;
filterreturns a new list. - This approach is concise, readable, and leverages Kotlin's functional programming features.