Created
November 5, 2024 15:53
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
please give me some star