can i accept `>`, `<=`, etc as an argument t...
# announcements
w
can i accept
>
,
<=
, etc as an argument to a function?
🚫 1
i could def do a lambda like
(Number, Number) -> Boolean)
as an arg but not sure about using
>
directly
m
@william Hello! Do you mean passing a boolean expression with
> or <=
to a function like below or something else?
Copy code
fun foo(a: Boolean) {}

fun main() {
    val a = 5
    val b = 6
    foo(a >= b)
}
m
@Margarita Bobova, I think he means passing an operator to a function and thus dynamically decide what to do
Copy code
fun main(){
    foo(6,5){ a,b -> a > b}
}

fun foo(a: Int, b: Int, comparator: (Int, Int) -> Boolean) = comparator(a,b)
m
You cannot pass a literal operator because it would be a syntactic error, neither pass a function reference because comparison operators are translated to
compareTo()
calls (https://kotlinlang.org/docs/reference/operator-overloading.html#comparison). The shortest you can get is to declare comparison lambdas as variables and pass them:
Copy code
fun test(x: Int, y: Int, f: (Int, Int) -> Boolean) = f(x, y)

val gt = { x: Int, y: Int -> x > y }
val gte = { x: Int, y: Int -> x >= y }
//etc...

fun main() {
    test(2, 1, gt)
    test(2, 2, gte)
}
w
thanks guys TIL they are translated to
compareTo