DEV Community

Cover image for crossinline in Kotlin
Amit Shekhar
Amit Shekhar

Posted on • Originally published at amitshekhar.me

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

This article was originally published at amitshekhar.me.

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()
}
Enter fullscreen mode Exit fullscreen mode

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");
}
Enter fullscreen mode Exit fullscreen mode

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()
}
Enter fullscreen mode Exit fullscreen mode

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");
}
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)