Kotlin 中缀函数:如何避免在提供的参数周围使用括号
我有以下中缀乐趣Kotlin 中缀函数:如何避免在提供的参数周围使用括号,kotlin,lambda,infix-notation,Kotlin,Lambda,Infix Notation,我有以下中缀乐趣 infix fun <T> Boolean.then(lazyValue: () -> T): T? = if (this) lazyValue() else null 我想把它改写成 index > 0 then { data[index - 1].id } 并避免在索引>0周围使用括号。目前它没有在代码中解析。 有什么办法可以让它工作吗?不,那不行 根据Kotlin语法参考中的,中缀函数调用的优先级,例如在您的例子中的then,高
infix fun <T> Boolean.then(lazyValue: () -> T): T?
= if (this) lazyValue() else null
我想把它改写成
index > 0 then { data[index - 1].id }
并避免在索引>0周围使用括号。目前它没有在代码中解析。
有什么办法可以让它工作吗?不,那不行
根据Kotlin语法参考中的,中缀函数调用的优先级,例如在您的例子中的then
,高于比较运算符
,=
因此,如果没有括号,像
index>0 then{…}
这样的表达式就像index>(0 then{…})
那样被解析,而不是相反的方式。不,这基本上就像问:我能在这里删除偏执吗(1+2)*3?不,你不能,因为那意味着不同的东西。谢谢。这似乎不可能。。
index > 0 then { data[index - 1].id }