Search code examples
kotlinlambdainfix-notation

infix function: how to avoid parentheses around supplied argument


I have the following infix fun

infix fun <T> Boolean.then(lazyValue: () -> T): T?
        = if (this) lazyValue() else null

with following use case

(index > 0) then { data[index - 1].id }

I want to rewrite it as

index > 0 then { data[index - 1].id }

and avoid parentheses around index > 0. Currently it does not resolve in code. Is there any way to make it work?


Solution

  • No, that won't work.

    According to the operator precedence table in the Kotlin Grammar reference, the precedence of infix function calls, such as then in your case, is higher than that of comparison operators <, >, <=, >=.

    So without parentheses, an expression like index > 0 then { ... } is parsed like index > (0 then { ... }) and not the other way.