How can I inline the receiver parameter of an extension function in Kotlin?

删除回忆录丶 提交于 2019-12-22 08:29:26

问题


Inspired by this question, I was thinking about how could one inline the receiver parameter of an extension function? In theory, like this:

inline fun <T> not(crossinline predicate : (T) -> Boolean)
    = { e : T -> !predicate(e) }

Just that predicate becomes our receiver function:

operator inline fun <T> ((T) -> Boolean).not()
    = { e : T -> !this(e) }

Now, for the above code, I'd expect the compiler to complain that it needs crossinline; however, I get the following warning:

Warning: Expected performance impact of inlining public inline operator fun <T> ((T) -> Boolean).not(): (T) -> Boolean is insignificant. Inlining works best for functions with parameters of functional types

This lets me believe that the compiler is not inlining the receiver of that function. Adding inline or crossinline only produces syntax errors.

Not being able to inline the second function decreases the performance over the first one.

Is there any way to tell the compiler to inline that receiver parameter?


回答1:


This is tracked in https://youtrack.jetbrains.com/issue/KT-5837, but doesn't seem to be actively worked on :( I actually just suggested supporting noinline/crossinline hoping that's the main reason receiver isn't inlined.



来源:https://stackoverflow.com/questions/52057967/how-can-i-inline-the-receiver-parameter-of-an-extension-function-in-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!