'Kotlin: How to create a higher order function that works inside suspend and non-suspend functions? (other than inline)

So basically, I want to create a high order function like run, that works inside non-functions as it works in suspend functions.

What seems to make it work is the inline modifier, but I'm sure that comes with some sort of overhead, so I'm wondering if there's another way.



Solution 1:[1]

I believe inline is the only way to achieve this. It is also a commonly used solution, both in stdlib and 3rd party code.

Regarding the overhead: it is actually the opposite. Higher-order functions are better to be inlined anyway - because of the performance. Drawback is the increased size of the resulting bytecode, so slightly increased memory usage. However, this shouldn't be a concern as long as the inlined function isn't really big.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 broot