Back to Blog

Kotlin Copilot: Divisible by 7

Sandy LaneSandy Lane

Video: Kotlin Copilot: Divisible by 7 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Kotlin Copilot: Divisible by 7

This example demonstrates how to count the number of elements in a list that are divisible by 7 using Kotlin. It uses Kotlin's functional programming features like filtering and lambda expressions to achieve this in a concise and readable way.

Code

fun main() {
  val numbers = listOf(14, 21, 33, 42, 55, 63, 70, 81)  // Sample list of integers

  // Filter numbers divisible by 7 and count them
  val divisibleBy7Count = numbers.count { it % 7 == 0 }

  println("Count of numbers divisible by 7: $divisibleBy7Count")
}

Key Points

  • Use the Kotlin list function count with a lambda to count elements matching a condition.
  • The modulo operator % helps check divisibility by 7.
  • Kotlin's concise syntax allows filtering and counting in a single expression.
  • Immutable lists can be processed efficiently with Kotlin's standard library functions.