crossinline in Kotlin

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

I am Amit Shekhar, Co-Founder @ Outcome School, 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 Outcome School and get high paying tech job: Outcome School

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 crossinline modifier in Kotlin.

What is a crossinline in Kotlin?

crossinline in Kotlin is used to avoid non-local returns.

Do not worry about the term "non-local returns", we will learn it with an example.

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

Let's take an example to understand the non-local returns.

fun guide() {
    print("guide start")
    teach {
        print("teach")
        return
    }
    print("guide end")
}

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

Here, we have added a return statement in the lambda function that we are passing.

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");
}

When we notice the decompiled code, we find that there is no System.out.print("guide end"). As we have added the return inside the lambda, it allowed the non-local returns and left the code below that.

Now, we have an idea of non-local returns.

How can we avoid this situation?

crossinline in Kotlin is the solution to avoid non-local returns.

When we add the crossinline, then it will not allow us the put the return inside that lambda.

Let's use the crossinline.

Our updated code with crossinline:

fun guide() {
    print("guide start")
    teach {
        print("teach")
        // return is not allowed here
    }
    print("guide end")
}

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

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");
    System.out.print("guide end");
}

Now, we can see that everything is as expected. We also have the System.out.print("guide end").

This is how the crossinline can help us to avoid the "non-local returns".

Now, we have understood the crossinline in Kotlin.

Learn about noinline: noinline in Kotlin

Prepare yourself for Android Interview: Android Interview Questions

That's it for now.

Thanks

Amit Shekhar
Co-Founder @ Outcome School

You can connect with me on:

Follow Outcome School on:

Read all of our high-quality blogs here.