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()
}
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With