noinline in Kotlin

Authors
  • Amit Shekhar
    Name
    Amit Shekhar
    Published on
noinline in Kotlin

I am Amit Shekhar, I have taught and mentored many developers, and their efforts landed them high-paying tech jobs, helped many tech companies in solving their unique problems, and created many open-source libraries being used by top companies. I am passionate about sharing knowledge through open-source, blogs, and videos.

Join my program and get high paying tech job: amitshekhar.me

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.

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

Prepare yourself for Android Interview: Android Interview Questions

That's it for now.

Thanks

Amit Shekhar

You can connect with me on:

Read all of my high-quality blogs here.