Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mahdiPourkazemi/dc03bd55375a7da36b49af8d4c83edc7 to your computer and use it in GitHub Desktop.
Save mahdiPourkazemi/dc03bd55375a7da36b49af8d4c83edc7 to your computer and use it in GitHub Desktop.
This Kotlin snippet showcases various ways to evaluate whether an integer is divisible by another integer using higher-order functions, member extension functions, and lambda references. It’s designed to illustrate Kotlin’s functional programming capabilities in a simple, clear manner.
// A higher-order function that executes a lambda function `f` on `arg1` with `arg2` as an argument.
fun exec(
arg1: Int, arg2: Int,
f: Int.(Int) -> Boolean
) = arg1.f(arg2) // Calls the lambda `f` with `arg2`.
// A lambda that checks if an integer is divisible by another integer.
val isDivisibleLambda: Int.(Int) -> Boolean = { this % it == 0 }
// An extension function for Int that checks if it is divisible by a given integer.
fun Int.isDivisibleExtension(d: Int): Boolean {
return this % d == 0
}
// A standard function that performs the divisibility check.
fun isDivisibleFunction(i: Int, d: Int): Boolean {
return i % d == 0
}
fun main() {
// Calls `exec` with an inline lambda function that checks divisibility.
exec(10, 2, fun Int.(d: Int): Boolean {
return this % d == 0
}) eq true // Asserts the result is true. (Make sure to explain `eq`.)
// Calls `exec` with the lambda `isDivisibleLambda`.
exec(10, 2, isDivisibleLambda) eq true // Asserts the result is true.
// Calls `exec` using the extension function `isDivisibleExtension`.
exec(10, 2, Int::isDivisibleExtension) eq true // Asserts the result is true.
// Calls `exec` using the top-level function `isDivisibleFunction`.
exec(10, 2, ::isDivisibleFunction) eq true // Asserts the result is true.
}
@mahdiPourkazemi
Copy link
Author

please give me some star

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment