问题
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