Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return from a top level function while inside an inner function in kotlin?

There are two functions, say func1 and func2. func2 is an inner function of func1 and based on a condition I wish to return from func1, meaning end execution of func1. How do I do that in kotlin?

fun func1(){
    fun func2(){
        if(someCondition){
            ...

            return@func1 //How do I do this? since it says return not allowed here
        }
    }

    ...

    func2()
}
like image 969
vepzfe Avatar asked Oct 27 '25 19:10

vepzfe


1 Answers

This wouldn't make sense in all cases, as a nested function might outlive the scope of the containing function in some cases. Here's an example of that:

var x: () -> Unit = {}

fun func1() {
    fun func2() {}

    x = ::func2
}

Here, it would not make sense to allow returns for func1 from func2. By the time x is called, there might not even be an active call to func1. This is basically the topic of non-local returns, which you need inline functions for (see the official documentation). Those, unfortunately, are not available as local functions (at least not yet).

For your specific case, you're probably stuck with signaling that you want a return from func1 by using the return value of func2 and checking for it in func1. (Or an exception, which wouldn't be nice to use for control flow like this.)

like image 151
zsmb13 Avatar answered Oct 30 '25 13:10

zsmb13