noinline in Kotlin

noinline in Kotlin

I am Amit Shekhar, a mentor helping developers in getting high-paying tech jobs.

Before we start, I would like to mention that, I have released a video playlist to help you crack the Android Interview: Check out Android Interview Questions and Answers.

In this blog, we will learn about the noinline modifier in Kotlin.

This article was originally published at amitshekhar.me.

What is a noinline in Kotlin?

Assume that we do not want all of the lambdas passed to an inline function to be inlined, in that case, we can mark those function parameters with the noinline modifier.

As we are learning about the noinline, we must be knowing about the inline keyword in Kotlin. You can learn here.

Let's understand this noinline modifier with an example.

fun guide() {
    print("guide start")
    teach({
        print("teach abc")
    }, {
        print("teach xyz")
    })
    print("guide end")
}

inline fun teach(abc: () -> Unit, xyz: () -> Unit) {
    abc()
    xyz()
}

Let's go to the decompiled code. The decompiled code is as below:

public void guide() {
    System.out.print("guide start");
    System.out.print("teach abc");
    System.out.print("teach xyz");
    System.out.print("guide end");
}

Here, both the lambdas(abc, xyz) passed to an inline function got inlined.

What if we want only the first lambda(abc) to get inlined but not the second lambda(xyz)?

In that case, we will have to use the noinline modifier with that lambda(xyz).

Our updated code:

fun guide() {
    print("guide start")
    teach({
        print("teach abc")
    }, {
        print("teach xyz")
    })
    print("guide end")
}

inline fun teach(abc: () -> Unit, noinline xyz: () -> Unit) {
    abc()
    xyz()
}

Again, let's go to the decompiled code. The decompiled code is as below:

public void guide() {
    System.out.print("guide start");
    System.out.print("teach abc");
    teach(new Function() {
        @Override
        public void invoke() {
            System.out.print("teach xyz");
        }
    });
    System.out.print("guide end");
}

public void teach(Function xyz) {
    xyz.invoke();
}

Here, we can see that the lambda(xyz) has not got inlined as expected. Only the lambda(abc) got inlined. This is how noinline in Kotlin helped us in achieving what we wanted.

This way, we used the noinline to avoid the inlining.

Now, we have understood the noinline in Kotlin.

Learn about crossinline: crossinline in Kotlin

Master Kotlin Coroutines from here: Mastering Kotlin Coroutines

That's it for now.

Thanks

Amit Shekhar

You can connect with me on:

Read all of my high-quality blogs here.