crossinline in Kotlin

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

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

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

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.