Kotlin-inline, crossline, noinline function and reified: Everything you need to know(Android) — Part 2

Ashiqul Islam Shaon
3 min readMay 14, 2022

If you didn’t read the part 1 then visit and read it first.

Let’s explore the noinline and crossline keyword in Kotlin.

NoInline

If you don’t want all of the lambdas passed to an inline function to be inlined, mark some of your function parameters with the noinline modifier. If you see the bytecode then there will be new instance of the function.

Here is the generated bytecode.

public final class TestInlineKt {
public static final void main() {
Function1 myAge$iv = (Function1)null.INSTANCE;
int $i$f$me = false;
String it = "Christiano";
int var3 = false;
System.out.println(it);
myAge$iv.invoke(36);
}

// $FF: synthetic method
public static void main(String[] var0) {
main();
}

public static final void me(@NotNull Function1 myName, @NotNull Function1 myAge) {
int $i$f$me = 0;
Intrinsics.checkNotNullParameter(myName, "myName");
Intrinsics.checkNotNullParameter(myAge, "myAge");
myName.invoke("Christiano");
myAge.invoke(36);
}
}

If you see carefully, one function is inlined and another function/lambda is not inlined. it creates a new instance of function.

Crossline

Let’s explore crossline keyword in kotlin.

To indicate that the lambda parameter of the inline function cannot use non-local returns, mark the lambda parameter with the crossline modifier.

inline fun f(crossinline body: () -> Unit) {
val f = object: Runnable {
override fun run() = body()
}
// ...
}

What does this mean?

First we need to understand what is non local returns. The best answer will give this doc.

fun main() {
me({
println(it)
}, {
return // non local return
println(it)
})

println("Do this")
}

inline fun me(myName: (String) -> Unit, myAge: (Int) -> Unit) {
myName("Christiano")
myAge(36)
}

Run this code, output will be only Christiano. Why didn’t it print “Do this’’?

Non local return statement make the code to exit from the main function.

If you use return@me inside age lambda you will Do this output. return@me only make the exit from the lambda function but return make the exit from the main function.

We can avoid non local return accident using crossline modifier.

Crossline

After using crossline modifier, IDE shows error. we can only use lambda return with the function name.

It is allowed and output will be.

Christiano
Do this

I hope you understand both of this modifier. Then give up big thumbs(50 like) and follow me for more.

--

--