F
F
foonfyrick2021-01-20 16:55:32
Kotlin
foonfyrick, 2021-01-20 16:55:32

Function call inline and constants?

Reading from the site:
A function can be easily inlined in the place from which it is called using the inline modifier.
The inline modifier affects both the function and the lambda passed to it: they will both be inlined at the call site.

I am reading the answer to my last question about const val and val:
After compilation, they disappear (they are not in the bytecode) and are substituted for the place of use.

My conclusion: It turns out that the principle of a constant and an inline modifier are similar? A constant is assigned at compile time and can't be assigned at runtime, so if the inline modifier, substitutes a function at compile time, this function can't be used at runtime? Correctly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2021-01-21
@foonfyrick

At some household level, it is similar, of course. Type, both that, and another is built in. But there are differences, of course.
There are situations when the compiler is required to inline a function because the JVM will not allow it otherwise, for example:

inline fun <reified T> f() {
    print(T::class.java.name)
}

reified generics are only supported for inline functions, because there are no generics in the JVM at run time, and therefore this function can only be used with a type known at compile time. The function body will be built into the call site and everything is fine.
But if you just have inline fun, regardless of whether it has a functional parameter, then options are already possible. With a normal call, the body of the function will be built in, and all sorts of extensions are based on this, they do not squander arbitrariness. But you can also take and pass this function to another as a parameter, in which case it simply has nowhere to inline:
inline fun f() { ... }
fun g(p: ()-> Unit) {
    p()
}

fun main() {
    f() // заинлайнена
    g(::f) // не заинлайнена
}

If you want to understand - see the decompiled bytecode, everything is there. Read more about noinline, crossinline modifiers.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question